我使用只有一个的程序运行quit = input.nextLine();
,但这会导致错误。但是,如果我两次使用该行,则不会发生错误,并且程序按预期运行。
为什么?
错误信息:Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at testjava.Test.main(Testjava.java:24)
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
boolean x = true;
boolean y = true;
Scanner input = new Scanner(System.in);
while (x) {
while (y) {
System.out.print("Enter -1 to quit ");
int val = input.nextInt();
if (val == -1)
y = false;
}
System.out.print("Are you sure you want to quit? (y/n) ");
String quit = input.nextLine();
quit = input.nextLine();
if (quit.charAt(0) == 'y')
x = false;
}
}