0

I'm making a simple method for a Java game with a class called DealOrNoDeal. It's a very simple method to get a int input from user between two bounds. But for some reason it thrown a java.lang.NullPointerException.

This is my code:

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; 
    }
asgs
  • 3,928
  • 6
  • 39
  • 54

1 Answers1

1

You re-declare the Scanner in this line:

Scanner scanner = new Scanner(System.in);

Remove the Scanner and your code should work:

scanner = new Scanner(System.in);

The null pointer is due to the fact that the first Scanner (the instance variable) is not initialized. You created a local variable called scanner that was named the same as the instance variable called scanner.

Chai T. Rex
  • 2,972
  • 1
  • 15
  • 33
Luvy
  • 96
  • 2