将第二条输入语句添加到代码后出错



code_1

Scanner input = new Scanner(System.in);
System.out.println("Enter Name : ");
String name = input.nextLine();
System.out.println("String name : " + name);
System.out.println("Enter age : ");
int age = input.nextInt();

代码_2

在这里,我试图同时获得姓名和年龄。这个代码取名字,在我输入名字后,它会打印错误,并且不要求年龄。。。

System.out.println("Enter Name and age : ");
String name = input.nextLine();
int age = input.nextInt();//error may be over here
System.out.println("String name : " + name);
System.out.println("String name : " + age);

问题是nextLine正在读取所有内容,所以nextIt没有可读取的内容。你想做的是。

1.读取输入

2.被某物分割(例如空间(

3.手工解析文本。

public static void main(String[] args) {
// Try-with-resources so its closes the scanner.
try (Scanner input = new Scanner(System.in);) {
System.out.println("Enter Name and age : ");
// Read input, split by spaces.
String[] text = input.nextLine().split(" ");
String name = "";
// Read the values, but not the last one.
for (int i = 0; i < text.length - 1; i++) {
name += text[i] + " ";
}
try {
// Take the last one and convert it to int.
int age = Integer.parseInt(text[text.length - 1]);
// Print if everything was ok.
System.out.println("String name : " + name);
System.out.println("String name : " + age);
} catch (NumberFormatException e) {
// The last field was not a number.
System.err.println("Age has to be a number");
}
} // No catch propagate the exception.
}

相关内容

  • 没有找到相关文章

最新更新