2016-10-01 23 views
-3
中返回-1

由於其他原因,該方法不會返回-1,所以我感到沮喪。我嘗試創建一個循環,但仍然給我返回-1的問題。我只想在用戶輸入負數時返回-1。我該怎麼做呢?如何在方法

如果輸入爲負,則該方法返回-1

public static int tringularNum(int num){ 
    int num1 = 0; 
    int sum = 0; 

    //Sum calculations 
    if (num > num1){ 
     System.out.print("("); 
     for (int i = 1; i <= num; i++){ 
      sum += i; 
      System.out.print(i+ "+"); 
     } 
     System.out.print(")"); 
     System.out.print(" = " + sum); 
    } 
    // Returns -1 if user enter a negative input 
    else 
     return -1; 
} 
+0

你的代碼需要返回if(){}和...它的作品。如果用戶輸入-1,則返回-1。 - >在線嘗試:https://repl.it/Dlqe – TessellatingHeckler

+0

考慮如果input = 0會發生什麼情況。還返回-1? – Nooblhu

回答

0

添加以下在上述方法的當前代碼:

if(num < 0) 
    return -1; 

這將檢查是否num小於0並返回-1而不繼續執行其餘的方法代碼。

+0

如果用戶輸入-3,我想讓用戶知道當他輸入一個負數時它返回-1 – Diend