import java.util.Scanner;
public class Hello {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int a;
String s;
System.out.println("Enter int : ");
a = in.nextInt();
System.out.println("Enter String : ");
s = in.nextLine();
System.out.println("int : "+a+"\nString : "+s);
}
}我完全是一个Java的初学者。我创建了Hello类,并希望输入一个数字和一个字符串,但我认为s = in.nextLine();这一行被忽略了。如何逐行输入两个值?
发布于 2012-07-13 14:25:25
当您使用Scanner.nextInt()时,它不使用新行(或其他分隔符)本身,因此返回的下一个标记通常是一个空字符串。因此,您需要在它后面加上一个Scanner.nextLine()。您可以丢弃结果,而不是将其赋值给a
int a = in.nextInt();
in.nextLine();出于这个原因,我建议始终使用nextLine (或BufferedReader.readLine()),并在使用Integer.parseInt()之后进行解析。
发布于 2012-07-13 14:17:31
而不是
s = in.nextLine();试一试
in.nextLine();
s = in.nextLine();对nextInt()的调用仍然会在后面留下一个换行符。
调用in.nextLine()实际上是转到下一行。然后in.nextLine会得到你的实际结果。
发布于 2012-07-13 14:30:13
像这样试试:D
import java.util.Scanner;
public class Hello {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int a;
String s = null;
System.out.print("Enter int: ");
a = in.nextInt();
while ((s = in.nextLine()).trim().isEmpty()) {
System.out.print("Enter String: ");
}
System.out.println("int : " + a + "\nString : " + s);
}
}https://stackoverflow.com/questions/11465066
复制相似问题