我输入:
然后发生的是,该循环再次发生,但是您无法再次输入your first and last name
。
String name = s.nextLine();
循环执行一次后,似乎总是空白行。
那是为什么?
代码:
Scanner s = new Scanner(System.in);
do {
System.out.printl('Enter your first and last name:');
String name = s.nextLine();
System.out.printl('Enter your job description:');
String job = s.nextLine();
System.out.println("Press Y for loop ..");
char answer = s.next().charAt(0);
} while(answer == 'Y');
答案 0 :(得分:2)
System.out.printl()
应该是System.out.println()
您应该对字符串使用双引号。
System.out.printl('Enter your first and last name:');//<----single quote
变量answer
超出范围,因为在Java中,范围限于{}
。在answer
循环之前(顶部)声明do-while
。
使用char answer = s.next().charAt(0);
代替使用answer = s.nextLine().charAt(0);
有关更多信息,请检查Scanner is skipping nextLine() after using next() or nextFoo()?
这是您修改的代码:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char answer; //<----declare the variable here
do {
System.out.println("Enter your first and last name:"); //<---use double quotes
String name = s.nextLine();
System.out.println("Enter your job description:");//<---use double quotes
String job = s.nextLine();
System.out.println("Press Y for loop ..");
answer = s.nextLine().charAt(0); //<---use nextLine() here
}while(answer == 'Y');
}