簡體   English   中英

Java if和else語句

[英]Java if and else statements

我正在嘗試用Java創建一個簡單的文本冒險游戲,當我鍵入Quit時,它結束了游戲。 但相反它會詢問你是否想要執行任務,即使你輸入quit,假設結束代碼,我嘗試使用循環來修復此錯誤,但不得不運氣。 知道我哪里錯了嗎?

import java.util.*;

public class TextGame {
    public static void main(String[] args) {

        //Boolean run = true;
        //while (run){

        Scanner in = new Scanner(System. in );

        System.out.println("~SPECTRE~");
        System.out.println("");
        System.out.println("Please Choose One Below");
        System.out.println("");
        System.out.println("New");
        System.out.println("Quit");
        System.out.println("");

        String option;
        System.out.print("Select one of the options here: ");
        option = in .next();

        if (option.equals("New")) {
            System.out.println("Hello adventurer! Welcome to the land of Spectre.");

            String name;
            System.out.print("What is your name adventurer? ");
            name = in .next();
            System.out.println("Hello there! " + name);
        } else if (option.equals("Quit")) {
            System.out.println("*Returns to desktop*");
        }

        String quest;
        System.out.print("Would you like to go on a quest? ");
        quest = in .next();

        if (quest.equals("Yes")) {
            System.out.println("Here is a list of quests that I would like you to do ");
            System.out.println("");
            System.out.println("1) Fight the evil troll of Port Howlham");
            System.out.println("");
            System.out.println("2) Deliver supplys to the soliders in need");
            System.out.println("");
            System.out.println("3) Find the Kings lost son");
            System.out.println("");
            System.out.println("4) Find the Gemstone of Darlingbee to defeat the evil witch of Hobbitstone");

        } else {
            option.equals("");
            System.out.println("*Please pick New Game or Quit*");
        }
    }
}

嘗試這個:

} else if (option.equalsIgnoreCase("Quit")) {
    System.exit(0);
}

或這個:

} else if (option.equalsIgnoreCase("Quit")) {
    return;
}

您可能希望退出該計划。 使用System.exit(0);

 else if(option.equals("Quit"))
{
    System.exit(0);
}

0參數是一個狀態代碼,表示程序的正常終止。

您可以使用System.exit(code)來完成該程序。 把它放在else if塊的末尾:

if (option.equals("Quit") {
    ...
    System.exit(0);
}

code可以是任何整數:

該參數用作狀態代碼; 按照慣例,非零狀態代碼表示異常終止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM