否则/如果输入没有打印正确的响应

时间:2018-04-17 18:44:53

标签: java arrays if-statement

程序询问用户问题并做出相应的响应。我正在使用带有if语句的ArrayLists来完成此任务。我无法理解为什么我的else / if代码不起作用。当我回复"北卡罗来纳州"我总是收到#34的最终回复;我从未猜到过!"

System.out.print("Where are you from? ");
    states.add(scanner.next());

    if (states.contains("Florida") || states.contains("florida")) {
        System.out.println("So was I!\n");
    } else {
    if (states.contains("North Carolina") || states.contains("north carolina")) {
        System.out.println("I hear that's a nice place to live.\n");
    } else {
            System.out.println("I would have never guessed!");
        }
    }

1 个答案:

答案 0 :(得分:0)

您的嵌套不正确。当您开始编写更大更复杂的程序时,您将学习如何简化代码以提高可读性。每当你有一堆ifif else语句时,代码很快就会变得难以阅读和/或调试。这就是我写它的方式。

 public static static void main(String args[]){
       List<String> states = new ArrayList<>();
       whereAreYouFrom(states);
    }

   public static void whereAreYouFrom(List<String> states){
           System.out.print("Where are you from? ");
           states.add(scanner.next());

            if (states.contains("Florida") || states.contains("florida")) {
              System.out.println("So was I!\n");
               return;
             }

            if (states.contains("North Carolina") || states.contains("north carolina")){ 
                System.out.println("I hear that's a nice place to live.\n");
                return;
             }

            System.out.println("I would have never guessed!");
      }

如果你想获得幻想,你可以使用switch语句,但老实说,以上方式可能对你将来调试最有帮助。