2013-10-21 133 views
0
System.out.print("Name : "); 
    String name = in.nextLine(); 

    System.out.print("Age : "); 
    int age = in.nextInt(); 

    System.out.print("City : "); 
    String city = in.nextLine(); 

输出将是:用户输入的字符串和整数在Java中

名称:测试

年龄:20

生成成功

当我进行调试,它赢得了”阅读“城市”的用户输入。但是当我将“年龄”的数据类型更改为字符串时,它会读取。我怎样才能使系统读取城市用户输入的数据类型为int?

+0

@ athirahhazira94,你已经经历关于nextLine()。 Anda kena baca tentang nextLine()。 – gjman2

回答

5

中仍存在的缓冲区的新行字符读岁以后,将其更改为..

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(); 
+1

发布*为什么*这种补充是必要的,只是针对遇到此问题的任何其他人可能会有所帮助。 –

+0

是的。我同意@dennis。为什么这是必要的? –

+0

我也同意,所以现在就完成了 –

2

还有在缓冲区的新行字符读岁以后。在询问城市价值之前,尝试添加in.nextLine

1

试试这个,

System.out.print("Age : "); 
int age = Integer.parseInt(in.nextLine()); 
相关问题