【问题标题】:How do I do a else if如果我该怎么做
【发布时间】:2022-11-12 17:45:26
【问题描述】:
/*
 * Activity 1.2.4
 */
import java.util.Scanner;

public class Main
{
  public static void main(String[] args)
  {
    Scanner sc = new Scanner(System.in);
    boolean isValidInput = false;
    boolean hasCandle = false;
    
    // The while loop should keep asking for input until the user provides a P or an E
    
    while (!isValidInput)
      {
      System.out.println("You are in a room with a small table and a lit candle.  There is a entrance to a tunnel to the east.  What would you like to do?");
      System.out.println("(p) Pick up the candle and enter the tunnel");
      System.out.println("(e) Enter the tunnel");
      String choice = sc.nextLine();

      if (choice == "p")
        isValidInput = true;
        hasCandle = true;
            System.out.println("With the candle in hand you enter the tunnel, the walls are splashed in a golden color, you keep walking reaching a corridor.");
            System.out.println("(e) Enter the first door");
            System.out.println("(k) Keep walking");
            String choice2a = sc.nextLine(); 
        
            else (choice == "e")
          isValidInput = true;
          hasCandle = false;
              System.out.println("You enter the tunnel, leaving the candle behind. The tunnel is pitch black. You use the wall to guide you. Not being able to see you fall into a room. Do you");
            System.out.println("(f) Find your way back out");
            System.out.println("(s) Stay in the room");
            String choice2b = sc.nextLine();
          
 
         
            

      }
  }
}

我在使用 else 选择 == e 时遇到了一些错误 它说tokan“else”上的语法错误,而预期 我不知道为什么会这样

【问题讨论】:

  • 对于多行块,您需要括号
  • 首先查找如何比较字符串。然后,这不是 Python - 您需要花括号来描述在“if”中运行的代码以及在“else”中运行的代码。

标签: java syntax-error token


【解决方案1】:

无括号 if/else 仅在后面有一个语句时才有效,如果还有更多则需要括号。字符串比较也是用equals 完成的(== 仅适用于原语,不适用于对象)

if (choice.equals("p")) {
    isValidInput = true;
    hasCandle = true;
    System.out.println("With the candle in hand you enter the tunnel, the walls are splashed in a golden color, you keep walking reaching a corridor.");
    System.out.println("(e) Enter the first door");
    System.out.println("(k) Keep walking");
    String choice2a = sc.nextLine();
} else (choice.equals("e")) {
    isValidInput = true;
    hasCandle = false;
    System.out.println("You enter the tunnel, leaving the candle behind. The tunnel is pitch black. You use the wall to guide you. Not being able to see you fall into a room. Do you");
    System.out.println("(f) Find your way back out");
    System.out.println("(s) Stay in the room");
    String choice2b = sc.nextLine();
}

【讨论】:

    【解决方案2】:

    否则没有条件。而是使用 else if(condition) 并添加括号。

    【讨论】:

      猜你喜欢
      • 2014-02-05
      • 2018-01-16
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2014-01-23
      • 2011-05-17
      • 1970-01-01
      相关资源
      最近更新 更多