Java 扫描器 sc.nextLine() 的问题;
对我的英语感到抱歉:)
我是 Java 编程新手,我对 Scanner 有疑问。我需要读取一个 Int,显示一些内容,然后读取一个字符串,所以我使用 sc.nextInt(); 显示我的内容 showMenu(); 然后尝试读取字符串 palabra=sc.nextLine();
有人告诉我我需要使用 sc.nextLine();在 sc.nextInt() 之后;但我不明白为什么你必须这样做:(
这是我的代码:
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int respuesta = 1;
showMenu();
respuesta = sc.nextInt();
sc.nextLine(); //Why is this line necessary for second scan to work?
switch (respuesta){
case 1:
System.out.println("=== Palindromo ===");
String palabra = sc.nextLine();
if (esPalindromo(palabra) == true)
System.out.println("Es Palindromo");
else
System.out.println("No es Palindromo");
break;
}
}
非常感谢你的时间和帮助:D
sry about my english :)
Im new to Java programming and i have a problem with Scanner. I need to read an Int, show some stuff and then read a string so i use sc.nextInt(); show my stuff showMenu(); and then try to read a string palabra=sc.nextLine();
Some one told me i need to use a sc.nextLine(); after sc.nextInt(); but i dont understand why do you have to do it :(
Here is my code:
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int respuesta = 1;
showMenu();
respuesta = sc.nextInt();
sc.nextLine(); //Why is this line necessary for second scan to work?
switch (respuesta){
case 1:
System.out.println("=== Palindromo ===");
String palabra = sc.nextLine();
if (esPalindromo(palabra) == true)
System.out.println("Es Palindromo");
else
System.out.println("No es Palindromo");
break;
}
}
Ty so much for your time and Help :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
nextInt()
仅读入,直到找到 int,然后停止。您必须执行
nextLine()
因为输入流仍然有换行符,并且该行上可能还有其他非 int 数据。调用nextLine()
读取剩余的所有数据,包括用户在输入 int 和输入 String 之间按下的 Enter。nextInt()
only reads in until it's found the int and then stops.You have to do
nextLine()
because the input stream still has a newline character and possibly other non-int data on the line. CallingnextLine()
reads in whatever data is left, including the enter the user pressed between entering an int and entering a String.当您输入一个值(无论是
String
、int
、double
等)并按“Enter”时,会出现一个换行符(又名'\n'
)将附加到您输入的末尾。因此,如果您输入 int,sc.nextInt()
将仅读取输入的整数,并将'\n'
留在缓冲区中。因此,解决此问题的方法是添加一个sc.nextLine()
来读取剩余内容并将其丢弃。这就是为什么您需要在程序中包含这一行代码。When you input a value (whether
String
,int
,double
, etc...) and hit 'enter,' a new-line character (aka'\n'
) will be appended to the end of your input. So, if you're entering an int,sc.nextInt()
will only read the integer entered and leave the'\n'
behind in the buffer. So, the way to fix this is to add asc.nextLine()
that will read the leftover and throw it away. This is why you need to have that one line of code in your program.