public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i=scan.nextInt();
// double d=scan.nextDouble();
// Write your code here.
Double d = 0.0;
try {
d = Double.parseDouble(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String s=scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
答案 0 :(得分:0)
您的代码可以更改为以下内容(请记住,关闭扫描仪总是一个好主意):
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
int i = scan.nextInt();
double d = scan.nextDouble();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
scan.close();
}
答案 1 :(得分:0)
这是因为当您输入数字并按Enter键时,scan.nextInt()
仅消耗输入的数字,而不是“行尾”。当scan.nextLine()
执行时,它会消耗您在执行scan.nextInt()
期间提供的第一个输入中仍在缓冲区中的“行尾”。
相反,请在scan.nextLine()
之后立即使用scan.nextInt()
。
在您当前的情况下,您将获得例外,
java.lang.NumberFormatException: empty String
您修改的代码将为,
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
scan.nextLine();
// double d=scan.nextDouble();
// Write your code here.
Double d = 0.0;
try {
d = Double.parseDouble(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}