If statement If语句跳过第一个用户输入扫描程序对象
程序段工作正常,但正在跳过if语句中的第一个任务 如果用户选择了Y,则输出如下 是否要添加另一主题代码-Y或N? y 输入主题名称: 输入主题代码: abc123 它没有给用户输入主题名称的机会。它在创建if语句之前就工作了,所以我假设它与此有关。我一直绞尽脑汁,但无济于事If statement If语句跳过第一个用户输入扫描程序对象,if-statement,java.util.scanner,If Statement,Java.util.scanner,程序段工作正常,但正在跳过if语句中的第一个任务 如果用户选择了Y,则输出如下 是否要添加另一主题代码-Y或N? y 输入主题名称: 输入主题代码: abc123 它没有给用户输入主题名称的机会。它在创建if语句之前就工作了,所以我假设它与此有关。我一直绞尽脑汁,但无济于事 System.out.println("Do you wish to add another subject code - Y or N? "); String response = input.next();
System.out.println("Do you wish to add another subject code - Y or N? ");
String response = input.next();
if (response.equalsIgnoreCase("Y")) {
/**User input*/
System.out.println("\nEnter the subject name: ");
String subjectName = input.nextLine();
System.out.println("\nEnter subject code: ");
String subjectCode = input.next();
Subject mySubject = new Subject(subjectCode, subjectName);
/**Write to the file*/
output.println(mySubject.getSubjectCode() + " " + mySubject.getSubjectName());
output.close();
}
else
output.close();
System.out.println("\nProgram terminated\n");
干杯,
苏珊
下一步,您只需阅读行的第一个单词
之后执行input.nextLine时,将一直读到下一行提要
这意味着,如果您键入y,第一条语句将读取y,第二条语句将一直读取,直到返回到空字符串。非常感谢!你对next和nextLine的解释非常好。
String response = input.next(); // Wrong
String response = input.nextLine(); // Right