2017-03-08 52 views
-1

所以我只是一個10年級的學生,我們正在做這個程序,我們會得到廣場,但它會拒絕負數使用嘗試,並抓住我的教授說我是唯一接近輸出但耗盡時間。使用try和catch獲得廣場

這是代碼。 它顯示的答案,但犯規拒絕負數,也不顯示「只有正數」 幫助PLS:d

import java.util.*; 
public class MySquare{ 
    public static void main(String args[]){ 
     int num; 
     int square; 

     Scanner s = new Scanner(System.in); 
     System.out.print("Input a number."); 
     num = s.nextInt(); 
      square = num * num; 
     System.out.println("Square: " + square); 
     try{ 

     if(num <0){ 


      throw new InputMismatchException("Only Positive Numbers!"); 
     } 
    }catch (InputMismatchException e){ 

    } 
+1

寫,如果條件之前計算方。 –

回答

0

你的catch塊是空的 - 這是一個非常糟糕的主意。永遠不要這樣做。

至少,你應該補充一點:

建議
} catch (InputMismatchException e) { 
    e.printStackTrace(); 
} 

一個字:瞭解並遵循嚴格的代碼風格。放置大括號,名稱等非常重要。

0

您已經關閉。試試這個:

public static void main(String args[]){ 
    int num; 

    Scanner s = new Scanner(System.in); 
    System.out.print("Input a number."); 

    try{ // try catch should surround s.nextInt, too 
     num = s.nextInt(); // read the input 

     if(num <0){ 
      throw new InputMismatchException("Only Positive Numbers!"); 
     } 
     // this part isnt reached in case of a negative number 
     int square = num * num; 
     System.out.println("Square: " + square); 
    }catch (InputMismatchException e){ 
     System.out.println("invalid input! " + e.getMessage()); // catch the exception and print its message (e.g. "Only Positive Numbers!" when a negative number is entered) 
    } 
} 
0

而不是InputMismatchException時使用拋出:IllegalArgumentException()

重構的代碼

import java.util.*; 
public class MySquare{ 
    public static void main(String args[]){ 
     int num; 
     int square; 
     Scanner s = new Scanner(System.in); 
     System.out.print("Input a number."); 
     num = s.nextInt(); 
     try { 
      if(num < 0){ 
       throw new IllegalArgumentException("Only Positive Numbers!"); 
      } 
      square = num * num; 
      System.out.println("Square: " + square); 
     } catch (IllegalArgumentException e) { 
      e.printStackTrace(); 
     } 
    } 

}