2016-12-11 8 views
1

これは、リストが空の場合、それは代わりにゼロを返すの例外をスローするようにどのように私はこのコードを変更できますか?私のコードこのコードに「例外をスローする」を追加するには?

public int Test(int[]n){ 
    if(n.length!=0){ 
     int smallest = n[0]; 
     for(int i = 0; i<n.length ; i++){ 
      if(smallest > n[i]){ 
       smallest = n[i]; 
       return smallest; 
      }else{ 
      return 0; 
     } 
    } 

} 

ですか

+0

を作成

このコードを試してみてください? – beatrice

+0

ops my bad!リターンステートメントを忘れてしまった! – In6ify

+1

@ In6ifyどの例外をスローしたいですか? – nullpointer

答えて

3

単にあなたの目標を達成することができます

public int Test(int[] n) { 
    if (n.length != 0) { 
     int smallest = n[0]; 
     for (int i = 0; i < n.length; i++) { 
      if (smallest > n[i]) { 
       smallest = n[i]; 
      } 
     } 
     return smallest; 
    } else { 
     throw new RuntimeException("List is empty!"); 
    } 
} 
0

次のように、他のブロックを変更することができます。

CustomExceptionあなたがスローする場合があります任意の例外を拡張することができ
if(n.length!=0){ 
    int smallest = n[0]; 
    for(int i = 0; i<n.length ; i++){ 
     if(smallest > n[i]){ 
      smallest = n[i]; 
      return smallest; // you might want to change this as well as suggested by @saeid 
     } else { 
      throw new CustomException(); 
     } 
    } 
} 

を。

0

空のリストを確認するだけで、空の場合は例外をスローするだけです。

throw new Exception("Your message that you want to show whenever the list is empty"). 

か、他

カスタム例外クラスを作成します。

class ListIsEmptyException extends Exception{ 
     //create constructors as per your need 
    } 

は今、リストが空の場合

throw new ListIsEmptyException(); 
0

return文は、内側にすることはできません「であればブロック」最初の比較が、それはあなたが返す必要があなたの条件に依存success.But場合、それが返されますので、メソッド。カスタム例外

パブリッククラスcustomExceptionあなたは1を返すようにしたいいけないときに、「int型の戻り値の型を持っていない理由{

public customException(String msg) { 

    super(msg); 
} 

}

if(n.length!=0){ 
    int smallest = n[0]; 
    for(int i = 0; i<n.length ; i++){ 
     if(smallest > n[i]){ 
      smallest = n[i]; 
      return smallest; 
     }else{ 
      throw new customException("Its an empty list!!!"); 
    } 
} 
関連する問題