0
Scanner sc = new Scanner (System.in);
String enter = new String ("Enter your name brave soul: ");
System.out.println (enter);
String name = sc.next();
System.out.println ("Your name is: " + name + "? Y/N");
boolean y = true; 
boolean n = false;
String yesorno = sc.next();

String intro1 = new String ("Welcome to Urieka! The objective of this game is quite simple, just find the key to escape.");


if (true) {System.out.println (intro1);}   //here
else if (false) {System.out.println (enter);} //here

我遇到了问题,如果用户输入 y,我想打印 intro1,如果他们输入错误,我希望提示输入名称。无论我输入 y 还是 no,它目前只打印 intro1。

此外,有没有办法让我再次运行该扫描仪,因为我假设如果我确实让它工作并且用户输入 n/false,那么它只会打印“输入你的名字勇敢的灵魂”而没有别的。我是否必须以某种方式将扫描仪添加到 else if 行的语句中?

4

4 回答 4

3
if (true) {System.out.println (intro1);}   //here

始终是正确的,并且将始终运行。else 同样永远不会运行。

你想要

if ("y".equalsIgnoreCase(yesorno)) {
   //...
}
于 2014-09-27T19:16:26.980 回答
3

嗯...true总是如此

if (true) { ... } 

将永远被执行。您应该执行以下操作:

System.out.println("y".equalsIgnoreCase(yesorno) ? intro1 : enter);
于 2014-09-27T19:17:47.307 回答
2

你永远不会改变这些布尔值:

boolean y = true;
boolean n = false;

还要尽量避免使用 if(true),如上一篇文章所述:

if (true) {System.out.println (intro1);}   //here

实例化 String 对象时,不必使用构造函数:

String enter = new String("Enter your name brave soul: ");
// IS THE SAME AS <=>
String enter = "Enter your name brave soul: ";

这是我对您的问题的解决方案:

Scanner scanner = new Scanner(System.in);
    boolean correctName = false;
    String name = "";

    while(!correctName){ //== Will run as long "correctName" is false. 
        System.out.println("Enter your name brave soul: ");
        name = scanner.next();
        System.out.println("Your name is: " + name + "? Y/N");
        String yesorno = scanner.next();
        correctName = "Y".equalsIgnoreCase(yesorno);  //== changes the boolean depending on the answer
    }
    System.out.println("Welcome to Urieka" + name + "! The objective of this game is quite simple, just find the key to escape.");
于 2014-09-27T19:39:11.253 回答
0

if (true) 意味着它总是会进入 if 条件并且总是会打印 intro01 。永远不会达到 else 条件。

你的情况应该是这样的:

if("y".equalsIgnoreCase(yesorno))
    System.out.println (intro1);
else
    System.out.println (enter);
于 2014-09-27T19:19:05.103 回答