if或then语句中的“或”各种字符串的条件

时间:2016-07-16 18:38:54

标签: java conditional-statements

我正在练习用Java编写代码,正在研究一个简单的程序,询问用户想要的类(来自Dungeons and Dragons)。收到数据后,我希望我的下一个问题是根据输入的类别显示武器列表。

我的问题在于第一个问题“问候,英雄......”。当用户输入无效的类时,我希望弹出一条消息,指出需要选择正确的类,然后为用户显示不同类的列表。我不确定如何正确编写“if..then”语句。

这个程序不完整,我停在我坚持的部分。

import java.util.Scanner;

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

        Scanner uinput = new Scanner(System.in);
        String firstclass, secondclass, multiclass, rogue, bard, fighter, wizard, sorcerer, monk, paladin, cleric, warlock, ranger;
        int dagger, shortsword, mace;

        System.out.println("Greetings hero, what profession do others call you?");
        firstclass = uinput.next();
        if(firstclass.equalsIgnoreCase("rogue") || ("bard") || "fighter" || "wizard" || "sorcerer" || "monk" || "paladin" || "cleric" || "warlock" || "ranger"));

        System.out.println("Aha! So we have a " +firstclass + " in our party!");
    }
}

1 个答案:

答案 0 :(得分:0)

这是编写代码最直接的方法,但正如其他人指出的那样,你可能想把所有“已知”类放到Set<String>中,这样你就可以轻松测试输入是否是在集合中,您也可以轻松打印出所有有效选项。

if(firstclass.equalsIgnoreCase("rogue") || firstclass.equalsIgnoreCase("bard") || firstclass.equalsIgnoreCase("fighter") || firstclass.equalsIgnoreCase("wizard") || firstclass.equalsIgnoreCase("sorcerer") || firstclass.equalsIgnoreCase("monk") || firstclass.equalsIgnoreCase("paladin") || firstclass.equalsIgnoreCase("cleric") || firstclass.equalsIgnoreCase("warlock") || firstclass.equalsIgnoreCase("ranger")) {
    System.out.println("Aha! So we have a " + firstclass + " in our party!");
} else {
    System.out.println("I don't know what a " + firstclass + " is.");
}
相关问题