2017-08-02 88 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