Java中的用户输入字符串和整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19485407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
user input string and integers in Java
提问by Athirah Hazira
System.out.print("Name : ");
String name = in.nextLine();
System.out.print("Age : ");
int age = in.nextInt();
System.out.print("City : ");
String city = in.nextLine();
the output will be :
输出将是:
Name : test
名称 : 测试
Age : 20
年龄 : 20
BUILD SUCCESSFUL
建造成功
when i debug them, it won't read the user input for "city" . but when i changed the data type for "age" to string, it will read. how can i kept the data type of age to int with the system reading the user inputs for city ?
当我调试它们时,它不会读取“城市”的用户输入。但是当我将“age”的数据类型更改为字符串时,它会读取。如何在系统读取城市用户输入的情况下将年龄的数据类型保持为 int ?
采纳答案by Scary Wombat
As there is still a new line character in the buffer after reading the age, change it to..
由于读取年龄后缓冲区中还有一个换行符,将其更改为..
System.out.print("Name : ");
String name = in.nextLine();
System.out.print("Age : ");
int age = in.nextInt();
//add
in.nextLine();
System.out.print("City : ");
String city = in.nextLine();
回答by MadProgrammer
There is still a new line character in the buffer after reading the age. Try adding a in.nextLine
before you ask for the city value.
读取年龄后缓冲区中仍然有一个换行符。in.nextLine
在询问城市值之前尝试添加 a 。
回答by newuser
Try this,
尝试这个,
System.out.print("Age : ");
int age = Integer.parseInt(in.nextLine());