2017-09-03 2 views
0

を投げたときに私は2つの和の問題へのJava溶液(ブルートフォース)をアップコーディングしようとしています:Javaの「エラー:タイプの違法開始」はIllegalArgumentException

import java.lang.*; 

public class TwoSum { 
    public int[] twoSum(int[] nums, int target) { 
     for (int i = 0; i < nums.length; i++) { 
      for (int j = i+1; j < nums.length; j++) { 
       if (nums[j] == target - nums[i]) { 
        return new int[] {i, j}; 
       } 
      } 
     } 
    } 
    throw new IllegalArgumentException("No two sum solution"); 
} 

しかし、ときに私それをコンパイルしようとしました。次のエラーが表示されます。

/home/kurt/Documents/Algorithms/TwoSum.java:13: error: illegal start of type 
    throw new IllegalArgumentException("No two sum solution"); 
    ^
/home/kurt/Documents/Algorithms/TwoSum.java:13: error: ';' expected 
    throw new IllegalArgumentException("No two sum solution"); 
     ^
/home/kurt/Documents/Algorithms/TwoSum.java:13: error: invalid method declaration; return type required 
    throw new IllegalArgumentException("No two sum solution"); 
      ^
/home/kurt/Documents/Algorithms/TwoSum.java:13: error: illegal start of type 
    throw new IllegalArgumentException("No two sum solution"); 
            ^
4 errors 
[Finished in 0.8s with exit code 1] 

エラーの原因になっている可能性がありますか? (私はコード例を抜粋したが、違いは気付かない)。コード次

+3

これは単にタイプミスです。メソッドの外側に 'throw' *を入れました。それをメソッドの '{...}'の中で1行上に移動します。入力/非再入力として閉じる投票。 –

+1

'throw new IllegalArgumentException(" No two sum solution ");はクラスレベルで宣言されています。それは許可されていません。最後のステートメントとして 'twoSum()'になければなりません。 – davidxxx

答えて

1

使用:この場合throw new IllegalArgumentException("No two sum solution");

import java.lang.*; 

public class TwoSum { 
    public int[] twoSum(int[] nums, int target) { 
     for (int i = 0; i < nums.length; i++) { 
      for (int j = i+1; j < nums.length; j++) { 
       if (nums[j] == target - nums[i]) { 
        return new int[] {i, j}; 
       } 
      } 
     } 
     throw new IllegalArgumentException("No two sum solution"); 
    } 
} 

は、メソッド内です。

関連する問題