循环字符串

时间:2016-03-23 15:27:09

标签: java loops if-statement while-loop

我正在为博物馆门票系统编写一个程序,用户可以在该系统中输入他们想要访问的展览,但是当输入无效时,程序会跳过if语句并继续执行其余的程序。

我在这里尝试的是当输入数据无效时,使程序循环回到if语句的开头。

while(invalidinput){
    if (userinput.equalsIgnoreCase("Roman")) {
        System.out.println("There are " +availabletic.getAvailabletickets1()+ " tickets available for the "+exhibit.getExhibit1());
        System.out.println("");
    } else if (userinput.equalsIgnoreCase("Warhol Art")){
        System.out.println("There are " +availabletic.getAvailabletickets2()+ " tickets available for the "+exhibit.getExhibit2());
        System.out.println("");

    } else if (userinput.equalsIgnoreCase("World War 2")) {
        System.out.println("There are " +availabletic.getAvailabletickets3()+ " tickets available for the "+exhibit.getExhibit3());
        System.out.println("");}

    } else if (!userinput.equalsIgnoreCase("Roman")
            && !userinput.equalsIgnoreCase("Warhol Art") 
            && !userinput.equalsIgnoreCase("World War 2"))
               invalidinput = false; // We signal that we may now leave the loop
       {
       System.out.println("Please enter a valid exhibition name");
    }               
}

2 个答案:

答案 0 :(得分:1)

这个条件:

else if (!userinput.equalsIgnoreCase("Roman")
            && !userinput.equalsIgnoreCase("Warhol Art") 
            && !userinput.equalsIgnoreCase("World War 2"))

必须替换为:

 else if (!userinput.equalsIgnoreCase("Roman")
            || !userinput.equalsIgnoreCase("Warhol Art") 
            || !userinput.equalsIgnoreCase("World War 2"))

答案 1 :(得分:0)

你不需要一个全能 - 如果。

if (userinput.equalsIgnoreCase("Roman"))
else if (userinput.equalsIgnoreCase("Warhol Art"))
else if (userinput.equalsIgnoreCase("World War 2"))
else // It's none of the others.