试图测试输入有效性

时间:2018-01-19 03:14:38

标签: java loops try-catch do-while

我今天一直在做一个小项目,在StackOverflow和其他地方寻找答案之后,我已经遇到了障碍。

我一直在尝试用Java创建一个自己冒险的冒险游戏,我首先要创建一个使用三个特征(名称,种族,性别)的角色。我计划使用这些来容纳故事中的分支。

问题在于我没有得到我正在寻找的结果。目前,我已经让我的代码工作了,打印声明显示了播放器的选择。

//list out character description

    System.out.println("You are " + Name + ", a " + characterGender + " " + 
    characterRace + ".");

我让它正常工作,直到我尝试对输入的输入执行测试,以根除无效的条目。我试图使用do-while循环和try-catch语句,但它只是向前运行到下一个选项,无论是否有有效输入。

我希望实施的一般想法是:

显示输入选项

检查输入以确认其有效

如果输入无效,请重新尝试检查其他输入

如果输入有效,请转到下一个问题

//create test to verify validity of race selection

    boolean raceBoolean;

    if (raceInt < 0 || raceInt > 4) {

        raceBoolean = true;

    try {

        do {

    //selection list that defines options

                if (raceInt == 1)
                    characterRace = "human";

                else if (raceInt == 2)
                    characterRace = "elf";

                else if (raceInt == 3)
                    characterRace = "orc";

                else if (raceInt == 4)
                    characterRace = "undead";

        }

        while (raceBoolean = false);

            System.out.println("Nice try. Enter a valid number for one of the four races!");

        }

            finally {

        }

老实说,我不知所措。我知道这很简单,但我试图自学。我感谢您提供的任何帮助。其他主题并不是非常有用,因为它们首先没有提供很多背景信息。

提前谢谢你。我老老实实地想要学习如何正确地做到这一点。

以下完整代码:

import java.util.Scanner;

public class Adventure {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    //insert input tool
    Scanner input = new Scanner(System.in);

    //create inventory object for gold and items
    int gold = 10;

    //create health points object 

    //address player with greeting
    System.out.println("Welcome to your adventure!");

    //ask for character name, race, and gender

    System.out.println("What will your adventurer's name be?");

    String Name = input.nextLine();

    System.out.println("What will your adventurer's race be?");
    System.out.println("1. Human");
    System.out.println("2. Elf");
    System.out.println("3. Orc");
    System.out.println("4. Undead");

    int raceInt = input.nextInt();

    String characterRace = "";

    //create test to verify validity of race selection

    boolean raceBoolean;

    if (raceInt < 0 || raceInt > 4) {

        raceBoolean = true;

    try {

        do {

    //selection list that defines options

                if (raceInt == 1)
                    characterRace = "human";

                else if (raceInt == 2)
                    characterRace = "elf";

                else if (raceInt == 3)
                    characterRace = "orc";

                else if (raceInt == 4)
                    characterRace = "undead";

        }

        while (raceBoolean = false);

            System.out.println("Nice try. Enter a valid number for one of the four races!");

        }

            finally {

        }

    }

    //ask for character gender

    System.out.println("What will your adventurer's gender be?");
    System.out.println("1. Male");
    System.out.println("2. Female");

    int genderInt = input.nextInt();

    String characterGender = "";

    if (genderInt == 1)
        characterGender = "male";

    else if (genderInt == 2)
        characterGender = "female";

    //list out character description

    System.out.println("You are " + Name + ", a " + characterGender + " " + characterRace + ".");

    //introduce player to adventure with different introductions for different races

    System.out.print("You came to Glassolin with only ten gold pieces to your name. ");

    if (characterRace == "human")
        System.out.print("Glassolin is home to many humans; some from the far reaches of the realm. You feel right at home, more or less,"
                + " as long as you ignore the occasional odd look from the cityfolk staring at someone dressed in farmer's clothes.");
    else if (characterRace == "elf")
        System.out.print("While an elf isn't the most common sight around town, the locals seem like they don't care one way or another "
                + "about you wandering the streets. ");


}

}

3 个答案:

答案 0 :(得分:1)

你比较给了while (raceBoolean=false)(赋值运算符)。其次是使用==运算符比较字符串。但是在java字符串中使用.equals()方法进行比较。我修改了你的代码。

这是完整的工作代码

import java.util.Scanner;

public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    //insert input tool
    Scanner input = new Scanner(System.in);

    //create inventory object for gold and items
    int gold = 10;

    //create health points object 

    //address player with greeting
    System.out.println("Welcome to your adventure!");

    //ask for character name, race, and gender

    System.out.println("What will your adventurer's name be?");

    String Name = input.nextLine();



    //create test to verify validity of race selection

    boolean raceBoolean=true;
    String characterRace = "";



    try {

        do {

    //selection list that defines options
                                 System.out.println("What will your adventurer's race be?");
                                System.out.println("1. Human");
                                System.out.println("2. Elf");
                                System.out.println("3. Orc");
                                System.out.println("4. Undead");

                                int raceInt = input.nextInt();
                                if (raceInt < 0 || raceInt > 4) {
                                raceBoolean = false;

                                }
                        else{
                                raceBoolean = true;
                            }

                if (raceInt == 1){
                    characterRace = "human";

                    }

                else if (raceInt == 2)
                    characterRace = "elf";

                else if (raceInt == 3)
                    characterRace = "orc";

                else if (raceInt == 4)
                    characterRace = "undead";
                System.out.println(raceInt);

        }
        while (raceBoolean==false);
        }

            finally {

        }



    //ask for character gender
    System.out.println("What will your adventurer's gender be?");
    System.out.println("1. Male");
    System.out.println("2. Female");

    int genderInt = input.nextInt();

    String characterGender = "";

    if (genderInt == 1)
        characterGender = "male";

    else if (genderInt == 2)
        characterGender = "female";

        System.out.println(characterRace);
    //list out character description

    System.out.println("You are " + Name + ", a " + characterGender + " " + characterRace + ".");

    //introduce player to adventure with different introductions for different races

    System.out.print("You came to Glassolin with only ten gold pieces to your name. ");

    if (characterRace.equals("human"))
        System.out.print("Glassolin is home to many humans; some from the far reaches of the realm. You feel right at home, more or less,"
                + " as long as you ignore the occasional odd look from the cityfolk staring at someone dressed in farmer's clothes.");
    else if (characterRace.equals("elf"))
        System.out.print("While an elf isn't the most common sight around town, the locals seem like they don't care one way or another "
                + "about you wandering the streets. ");


}

}

答案 1 :(得分:0)

这里易于解决的问题, 你刚才在if语句中出现了逻辑错误

if (raceInt < 0 || raceInt > 4) {

检查raceInt是小于0还是大于4

但我们希望看看是否符合(0,4)的范围(您的分类是1,2,3和4) 所以我们想要的是:     if(raceInt&gt; 0&amp;&amp; raceInt&lt; = 4)

switch case语句将是一种更好的可读方式

while (characterRace.isEmpty()) {
    switch (raceInt) {
            case 1:
                characterRace = "human";
                break;
            case 2:
                characterRace = "elf";
                break;
            case 3:
                characterRace = "orc";
                break;
            case 4:
                characterRace = "undead";
                break;
            default:
                System.out.println("Nice try. Enter a valid number for one of the four races!");
                break;
    }
}

顺便说一句: 属性/变量的名称约定是非大写的(因此只需将变量Name更改为name)

您也可能想要注意有更好的方法来做这些事情 https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

答案 2 :(得分:0)

从以下开始:

  System.out.println("4. Undead");

此代码应继续询问有效答案,直到给出答案。

//create test to verify validity of race selection  
String characterRace = "";
boolean raceBoolean = false;

Do{
int raceInt = input.nextInt();

    if (raceInt == 1){
        characterRace = "human";
        raceBoolean = true;
        }else{
            if (raceInt == 2){
            characterRace = "elf";
            raceBoolean = true;
            }else{
                if (raceInt == 3){
                characterRace = "orc";
                raceBoolean = true;
                }else{
                    if (raceInt == 4){
                    characterRace = "undead";
                    raceBoolean = true;
                    }else{
                        raceBoolean = false;
                        System.out.println("Nice try. Enter a valid number for one of the four races!");
                    }
                }
            }
        }
    }while(raceBoolean = false)

它将输入放在do while语句中,以便它可以重复请求不同的输入。此外,我将布尔值初始化为false,就像故障安全一样。最后的while语句测试是否给出了有效的输入。

使用嵌套的if / else语句进行测试。