在Java中,如何在控制台中从用户获得简单的键盘输入(整数)?我使用java.io.*
实现了这一点,但它显示它已被弃用。
我现在该怎么做呢?
发布于 2013-07-09 08:46:31
您可以使用Scanner类
首先导入:
import java.util.Scanner;
然后像这样使用。
Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();
附注:如果你将nextInt()
和nextLine()
一起使用,你可能会遇到一些问题,因为nextInt()
不会读取输入的最后一个换行符,所以nextLine()
不会以期望的行为执行。在上一个问题Skipping nextLine using nextInt中阅读有关如何解决它的更多信息。
发布于 2013-07-09 08:47:07
您可以像这样使用Scanner类:
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);
}
}
发布于 2013-07-09 09:09:55
如果您想验证用户输入,也可以使用BufferedReader,如下所示:
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“调用。
https://stackoverflow.com/questions/17538182
复制相似问题