在if语句中放入if-else语句(Eclipse上的Java)

时间:2015-06-03 17:42:31

标签: java eclipse if-statement curly-brackets

我正在处理我的java类的一些任务,我遇到了这个错误:

public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";

public static void main(String[] args) {
    Scanner myScanner = new Scanner(System.in);
    System.out.println("Welcome to QuizApp! Programmed by Chris!");
    System.out.println("Please type the number corrisponding to the correct answer.");
    int score = 100;
    for(int i = 0;i <5;i++) {
        if (i == 0) {
            System.out.println("What is the capital of America? ");
            System.out.println("1) Washington D.C \t2) New York");
            System.out.println("3) Philadelphia \t4) Manhatten");
            int answer = myScanner.nextInt();
            if (answer == 1) {
                System.out.println(ANSI_GREEN+"Correct!");
            }else{
                System.out.println("Either your answer was wrong, or there was a syntax error.");
                score = score - 20;
            }
            if (i == 1) {
                System.out.println("What ocean do emporer penguins swim in? ");
                System.out.println("1) The Indian Ocean \t2) The Pacific Ocean");
                System.out.println("3) The Atlantic Ocean \t4) The Antarctic Ocean");
                answer = myScanner.nextInt();
                if (answer == 4); {
                    System.out.println(ANSI_GREEN+"Correct!");
                }else{
                    System.out.println(ANSI_RED+"Either your answer was wrong, or there was a syntax error.");
                }
            }           
        }   
    }
}

}

它说我的花括号出错了:

        if (i == 1) {
            System.out.println("What ocean do emporer penguins swim in? ");
            System.out.println("1) The Indian Ocean \t2) The Pacific Ocean");
            System.out.println("3) The Atlantic Ocean \t4) The Antarctic Ocean");
            answer = myScanner.nextInt();
            if (answer == 4); {
                System.out.println(ANSI_GREEN+"Correct!");
            }else{
                    System.out.println(ANSI_RED+"Either your answer was wrong, or there was a syntax error.");
            }
        }

我试图在if语句中放入if-else语句。我知道为什么它给我这个错误,但我不知道如何解决它。 (错误很可能是java认为} else {与第一个if语句配对。

1 个答案:

答案 0 :(得分:3)

问题出在这里

if (answer == 4);

if语句后面有分号,终止条件。删除它,你应该没事。