我是编程新手,这个问题一直困扰着我 当我运行程序时,Java 会忽略 if 中的字符串输入 我做错了什么?
import java.util.Scanner;
public class JavaApplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("------ FEEDBACK/COMPLAINT ------\n"
+ "-------------------------------------\n"
+ "| 1: Submit Feedback |\n"
+ "| 2: Submit Complaint |\n"
+ "| 3: Previous Menu |\n"
+ "-----------------------------------\n"
+ "> Please enter the choice: ");
int feedorcomw = input.nextInt();
if (feedorcomw == 1) {
String name;
System.out.print("> Enter your name (first and last): ");
name = input.nextLine();
System.out.println("");
System.out.print("> Enter your mobile (##-###-####): ");
int num = input.nextInt();
}
}
}
最佳答案
您忽略了 Scanner#nextInt 方法不会消耗您输入的最后一个换行符这一事实,因此在下一次调用 Scanner#nextLine时会消耗该换行符强>
尝试添加 input.nextLine();
之后一切都会正常进行
示例:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("------ FEEDBACK/COMPLAINT ------\n"
+ "-------------------------------------\n"
+ "| 1: Submit Feedback |\n"
+ "| 2: Submit Complaint |\n"
+ "| 3: Previous Menu |\n"
+ "-----------------------------------\n"
+ "> Please enter the choice: ");
int feedorcomw = input.nextInt();
input.nextLine();
if (feedorcomw == 1) {
String name;
System.out.print("> Enter your name (first and last): ");
name = input.nextLine();
System.out.println("");
System.out.print("> Enter your mobile (##-###-####): ");
int num = input.nextInt();
}
}
关于Java忽略字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36521153/