2017-08-02 94 views
-3
import java.util.Scanner; 

public class HelloWorld { 
    public static void main(String[] args) { 
     // Prints "Hello, World" in the terminal window. 

     Scanner quest = new Scanner(System.in);enter code here 
     System.out.println("How old are you?: "); 
     int num = quest.nextInt(); 

     if (num <= 12){ 
     System.out.println("You are too young to be on the computer!!!!"); 
     } else if (num >=13 && num <= 17){ 
     System.out.println("Welcome young teen"); 
     } else if (17 < num && num <= 60){ 
     System.out.println("Welcome adult"); 
     } else if (60 < num){ 
     System.out.println("Welcome senior citizen!!"); 
     } else{ 
     System.out.println("Invalid age."); 
     } 

    } 
} 

当我输入一个负数时,它只属于“你太年轻了,不能在电脑上!!!!”而不是显示“无效的年龄”。我试图改变条件,但它似乎没有工作。负数不被识别

+0

这是因为这是第一个条件。做'num <= 12 && num> 0'什么的。 – Li357

+0

负值使第一个“if”为真,然后显示它所显示的内容。 – SHG

+2

该死的新的数学模式,其中-1> 12! – John3136

回答

1

由于负数小于12,你可以通过测试负值,依靠先前免除了您&&检查,检查的条件简化您的if-else块链。 Like,

int num = quest.nextInt(); 
if (num < 0) { // <-- negative values. 
    System.out.println("Invalid age."); 
} else if (num <= 12) { // <-- (0, 12) 
    System.out.println("You are too young to be on the computer!!!!"); 
} else if (num <= 17) { // <-- (13, 17) 
    System.out.println("Welcome young teen"); 
} else if (num <= 60) { // <-- (18, 60) 
    System.out.println("Welcome adult"); 
} else { // <-- greater than 60 
    System.out.println("Welcome senior citizen!!"); 
} 
0

您应该已将其作为if(Condition) { //Code }声明的第一条件。那么我做了一个代码运行,并对代码做了一些调整。

import java.util.Scanner; 

public class HelloWorld { 
    public static void main(String[] args) { 
     // Prints "Hello, World" in the terminal window. 

     Scanner quest = new Scanner(System.in); //enter code here 
     System.out.println("How old are you?: "); 
     int num = quest.nextInt(); 

     if (num <= 0) { 
      System.out.println("Invalid age."); 
     } else if (num <= 12){ 
     System.out.println("You are too young to be on the computer!!!!"); 
     } else if (num >=13 && num <= 17){ 
     System.out.println("Welcome young teen"); 
     } else if (17 < num && num <= 60){ 
     System.out.println("Welcome adult"); 
     } else if (60 < num){ 
     System.out.println("Welcome senior citizen!!"); 
     } 
    } 
} 
+0

谢谢你们俩,真的有帮助。也帮助我简化了我的代码。它已经有一段时间了,因为我已经编码,所以我的逻辑仍然不存在。 –

+0

如果我的回答或任何其他用户回答有助于解决您的问题,请将其标记为已回答并向上投票@GabeGomez – Eazy