首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取键盘输入

获取键盘输入
EN

Stack Overflow用户
提问于 2013-07-09 08:41:01
回答 7查看 549.8K关注 0票数 46

在Java中,如何在控制台中从用户获得简单的键盘输入(整数)?我使用java.io.*实现了这一点,但它显示它已被弃用。

我现在该怎么做呢?

EN

回答 7

Stack Overflow用户

发布于 2013-07-09 08:46:31

您可以使用Scanner

首先导入:

代码语言:javascript
复制
import java.util.Scanner;

然后像这样使用。

代码语言:javascript
复制
Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();

附注:如果你将nextInt()nextLine()一起使用,你可能会遇到一些问题,因为nextInt()不会读取输入的最后一个换行符,所以nextLine()不会以期望的行为执行。在上一个问题Skipping nextLine using nextInt中阅读有关如何解决它的更多信息。

票数 73
EN

Stack Overflow用户

发布于 2013-07-09 08:47:07

您可以像这样使用Scanner类:

代码语言:javascript
复制
  import java.util.Scanner;

public class Main{
    public static void main(String args[]){

    Scanner scan= new Scanner(System.in);

    //For string

    String text= scan.nextLine();

    System.out.println(text);

    //for int

    int num= scan.nextInt();

    System.out.println(num);
    }
}
票数 21
EN

Stack Overflow用户

发布于 2013-07-09 09:09:55

如果您想验证用户输入,也可以使用BufferedReader,如下所示:

代码语言:javascript
复制
import java.io.BufferedReader;
import java.io.InputStreamReader; 
class Areas {
    public static void main(String args[]){
        float PI = 3.1416f;
        int r=0;
        String rad; //We're going to read all user's text into a String and we try to convert it later
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
        System.out.println("Radius?");
        try{
            rad = br.readLine(); //We read from user's input
            r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call))
            System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this
        }
        catch(Exception e){
            System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer
            Areas a = new Areas(); //We call this class again, so user can try it again
           //You can also print exception in case you want to see it as follows:
           // e.printStackTrace();
        }
    }
}

因为Scanner类不允许你这样做,或者说不是那么简单…

为了验证,可以使用"try-catch“调用。

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17538182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档