2017-10-30 22 views
0

나는 DealOrNoDeal 클래스로 자바 게임을위한 간단한 메소드를 만들고 있습니다. 두 경계 사이에서 사용자로부터 int 입력을받는 것은 매우 간단한 방법입니다. 그러나 웬일인지 그것은 java.lang.NullPointerException를 던졌다.간단한 자바 메소드 getIntBetweenBounds가 NullPointerException 오류를 발생했습니다.

scanner = new Scanner(System.in); 

:

Scanner scanner = new Scanner(System.in); 

Scanner와 코드가 작동합니다 제거 :이 줄에 Scanner를 다시 선언

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

'this.scanner = new Scanner (System.in);에 의해'Scanner scanner = new Scanner (System.in);를 변경하면 어떨까요? – Rafa

답변

1

:

내 코드입니다 null 포인터는 첫 번째 사실이 원인입니다. Scanner (인스턴스 변수)이 초기화되지 않았습니다. scanner이라는 인스턴스 변수와 동일한 이름의 scanner이라는 로컬 변수를 만들었습니다.

+0

코멘트로 게시 할 필요가 없습니다. 이것은 유효한 대답입니다. –