我正在尝试实现一种方法,让玩家选择用户名。该方法根据当前运行的操作系统的用户名建议一个。现在,如果他/她对建议不满意,我想给用户一个更改其昵称的选项。现在的问题是,我总是不得不两次输入我的声明,因为我猜其中任何一个都不会被接受。
(例如,我必须输入:
“ y”
“ y”)
我尝试在while循环中更改语句(例如“ nameChange.hasNextLine()”)。我尝试添加“ nameChange.nextLine();”在“ line = nameChange.nextLine();”之前和之后(如关于SO的类似文章所建议),但均未奏效。
public class SetUsername implements Runnable {
/**
* Suggests a name based on the accessing OS's user Let's the user change the suggestion to his
* or her own username.
*/
@Override
public void run() {
String name = System.getProperty("user.name");
Scanner nameChange = new Scanner(System.in);
System.out.println("Your username is: " + name + ". Would you like to change it? (y/n)");
String line;
while (true) {
line = nameChange.nextLine();
if (line.equals("y")) {
System.out.println("Chose a new username:");
while(true) {
name = nameChange.nextLine();
System.out.println("Your new username is "+ name);
break;
}
break;
} else if (line.equals("n")) {
break;
} else {
System.out.println("Invalid input. Your username is: " + name + ". "
+ "Would you like to change it? (y/n)");
}
}
send(Command.SET_USERNAME, name);
}
}
答案 0 :(得分:1)
“在调用next()或nextInt()结束之前,您可能还有其他方法正在运行,因此不会占用行的结尾。” – JB Nizet
那是问题。