[Java]嵌套if else语句+多个System.out.print命令

时间:2017-03-21 02:54:27

标签: java if-statement nested println

我需要一些帮助来弄清楚为什么这不起作用。是否可能只是嵌套的if-else语句或if-else语句的规则,通常只允许一个System.out.print语句? 我需要输出 "可能有安全带。 可能有防抱死制动器。"

等等到2000年。

代码:

public class CarFeatures {
   public static void main (String [] args) {
      int carYear = 0;

      carYear = 1990;

      if (carYear <= 1969) {
         System.out.println("Probably has few safety features.");

      }else{
         if (carYear >= 1970) {
            System.out.println("Probably has seat belts.");

         }else{
            if (carYear >= 1990) {
               System.out.println("Probably has seat belts.");
               System.out.println("Probably has anti-lock brakes.");

         }else{
             if (carYear >= 2000) {
               System.out.println("Probably has seat belts.");
               System.out.println("Probably has anti-lock brakes.");
               System.out.println("Probably has air bags.");

             }
            }
         }
      }
      return;
   }
}

3 个答案:

答案 0 :(得分:0)

因为这个

 if (carYear >= 1970) {
        System.out.println("Probably has seat belts.");

     }else{

     }
1990年&gt; 1970年,所以只需打印“可能有安全带。”

答案 1 :(得分:0)

if{...} else {...} else will not be entered into if the if`为真

删除它们

 if {
    ...
 }else{
     if (carYear >= 1970) {
        System.out.println("Probably has seat belts.");

     }
     if (carYear >= 1990) {
           System.out.println("Probably has seat belts.");
           System.out.println("Probably has anti-lock brakes.");

     }
      if (carYear >= 2000) {
           System.out.println("Probably has seat belts.");
           System.out.println("Probably has anti-lock brakes.");
           System.out.println("Probably has air bags.");

      }
 }

答案 2 :(得分:0)

出现此问题是因为1990大于或等于1990,但它也大于或等于1970。因为1970语句首先出现在代码中,所以它永远不会到达1990语句。

要解决此问题,您的代码中可能会出现各种优化:

  1. 您可以在一行上声明{init} carYear 1990
  2. 在嵌套级别使用if语句而不是else语句,不必复制print语句。
  3. 尝试以下代码here!

    public class CarFeatures {
      public static void main (String [] args) {
        int carYear = 1990;
    
        if (carYear <= 1969) {
          System.out.println("Probably has few safety features.");
        } else {
          if (carYear >= 1970) {
            System.out.println("Probably has seat belts.");
          } 
          if (carYear >= 1990) {
            System.out.println("Probably has anti-lock brakes.");
          }
          if (carYear >= 2000) {
            System.out.println("Probably has air bags.");
          }
        }
      }
    }