我正在制作一个游戏,它会提示您输入您的名字,然后输入您的名字,它要求您通过输入“ N”或“ Y”进行确认。按下N后,它虽然返回输入但不提示您这样做,因此不会打印任何内容,因为它不会打印其他任何内容。只有Y起作用。我已经尝试了一切,但是没有用。
这是我用来确认名称的代码:
private static void comfirmName() {
System.out.println("Is " + name + " your name?");
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Y/N");
if (input.nextLine().toUpperCase().equals("Y")) {
System.out.println("There is something you should know...");
}
if (input.nextLine().toUpperCase().equals("N")) {
System.out.println("Enter your name:");
name = input.nextLine();
System.out.println("Is " + name + " your name?");
}
if (!input.nextLine().toUpperCase().equals("N") && !input.nextLine().toUpperCase().equals("Y")) {
System.out.println("Please enter Y or N");
}
}
这是输出:
Welcome to Enchanted Mage!
Here we will venture into the dangers of this planet!
First of all, you must tell me your name, venturer!
Type in your name:
ots wng
Hello there ots wng!
Is ots wng your name?
Y/N
n
otswng
nothing is hapening
ummm
Please enter Y or N
BUILD SUCCESSFUL
没有错误,但输出任何输出确实很烦人。
答案 0 :(得分:1)
只需在输入ifs之前添加一个输入,就像这样:
String inputAnswer = input.nextLine().toUpperCase();
为了更加简洁,只需将ifs内的input.nextLine更改为刚创建的变量,就像这样:
if(inputAnswer.equals("Y")){
System.out.println("There is something you should know...");
}
我刚刚测试了一下,它可以工作。随时问其他问题!
答案 1 :(得分:0)
仅读取一次确认信息。
private static void comfirmName() {
System.out.println("Is " + name + " your name?");
System.out.println("Y/N");
String confirmation = input.nextLine().toUpperCase(); //Read only once the user confirmation
if (confirmation.equals("Y")) {
System.out.println("There is something you should know...");
}
if (confirmation.equals("N")) {
System.out.println("Enter your name:");
name = input.nextLine();
System.out.println("Is " + name + " your name?");
}
if (!confirmation.equals("N") && !confirmation.equals("Y")) {
System.out.println("Please enter Y or N");
}
}
输出
Is Dan your name?
Y/N
n
Enter your name:
Dan
Is Dan your name?