2017-10-30 12 views
0

私はDealOrNoDealというクラスのJavaゲームのための簡単なメソッドを作っています。 2つの境界の間でユーザーからのint入力を取得する方法は非常に簡単です。しかし何らかの理由でそれはjava.lang.NullPointerExceptionを投げた。単純なJavaメソッドgetIntBetweenBoundsはNullPointerExceptionエラーを返します

これは私のコードです:

import java.util.Scanner; 
import java.util.Arrays; 
public class DealOrNoDeal { 
    public Scanner scanner; 
    public static void main(String[] args) { 
     new DealOrNoDeal().run(); 
    } 
    public void run() { 
     Scanner scanner = new Scanner(System.in); 
     int[] values = {1, 20, 100, 1000, 2000, 5000}; 

     System.out.println("Please select the suitcase that you would like to keep (1-6): "); 
     int keuze = getIntBetweenBounds(1, 6); 
    } 
    private int getIntBetweenBounds(int lowerBound, int upperBound) { 
     int result = scanner.nextInt(); 
     System.out.println("Please select the suitcase that you would like to keep (1-6): "); 
     while (result < lowerBound || result > upperBound) { 
      System.out.println("Please select the suitcase that you would like to keep (1-6): "); 
      result = scanner.nextInt(); 
     } 
     return result; 
    } 
+0

スタックトレースを投稿できますか? –

+0

スタックトレースとはどういう意味ですか? –

+0

'スキャナスキャナ=新しいスキャナ(System.in);を' this.scanner = new Scanner(System.in);で変更するとどうでしょうか? – Rafa

答えて

1

あなたはこの行のScannerに再宣言:

Scanner scanner = new Scanner(System.in); 

Scannerを削除し、あなたのコードは動作するはずです:

scanner = new Scanner(System.in); 

nullポインタは、最初のポインタがScanner(インスタンス変数)は初期化されていません。 scannerというインスタンス変数と同じ名前のローカル変数scannerを作成しました。

+0

コメントとして投稿する必要はありません。これは有効な答えです。 –

関連する問題