Java 循环中的扫描器仅获取第一个输入
Java Scanner in Loop only gets first input
我正在尝试使用 for 循环从用户那里获取多个输入。在该循环中,我正在调用一个包含扫描仪的函数。当我只调用一次函数时,程序运行良好。但是在一个循环中,只有第一次调用该函数时它才能正常工作。我在下面创建了一个简化的程序示例。我怎样才能改变它,使循环的其他迭代也能正常工作?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String response = "";
for(int inputNr = 0; inputNr <=2; inputNr++) {
response = getResponse();
System.out.println(response);
}
}
public static String getResponse() {
String response = "";
System.out.println("Enter a String");
Scanner userInput = new Scanner(System.in);
if(userInput.hasNextLine()) {
response = userInput.nextLine();
}
userInput.close();
return response;
}
}
结果看起来像
Enter a String
This is what I entered...
This is what I entered...
Enter a String
Enter a String
您正在关闭链接到标准输入流 System.in
的 Scanner
对象。这会导致 System.in
关闭,因此不再接受输入。在下一次迭代中 userInput.hasNextLine()
returns false
。创建 Scanner
的单个实例并在循环的所有迭代为 运行.
后关闭它
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
String response = "";
for (int inputNr = 0; inputNr <= 2; inputNr++) {
response = getResponse();
System.out.println(response);
}
userInput.close();
}
public static String getResponse() {
String response = "";
System.out.println("Enter a String");
if (userInput.hasNextLine()) {
response = userInput.nextLine();
}
return response;
}
我正在尝试使用 for 循环从用户那里获取多个输入。在该循环中,我正在调用一个包含扫描仪的函数。当我只调用一次函数时,程序运行良好。但是在一个循环中,只有第一次调用该函数时它才能正常工作。我在下面创建了一个简化的程序示例。我怎样才能改变它,使循环的其他迭代也能正常工作?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String response = "";
for(int inputNr = 0; inputNr <=2; inputNr++) {
response = getResponse();
System.out.println(response);
}
}
public static String getResponse() {
String response = "";
System.out.println("Enter a String");
Scanner userInput = new Scanner(System.in);
if(userInput.hasNextLine()) {
response = userInput.nextLine();
}
userInput.close();
return response;
}
}
结果看起来像
Enter a String
This is what I entered...
This is what I entered...
Enter a String
Enter a String
您正在关闭链接到标准输入流 System.in
的 Scanner
对象。这会导致 System.in
关闭,因此不再接受输入。在下一次迭代中 userInput.hasNextLine()
returns false
。创建 Scanner
的单个实例并在循环的所有迭代为 运行.
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
String response = "";
for (int inputNr = 0; inputNr <= 2; inputNr++) {
response = getResponse();
System.out.println(response);
}
userInput.close();
}
public static String getResponse() {
String response = "";
System.out.println("Enter a String");
if (userInput.hasNextLine()) {
response = userInput.nextLine();
}
return response;
}