0

The code im working on is intended to accept an input from the user but whenever i run the program, it keeps telling me that there is an error, the java.land.nullexception: null. I dont know what to do!

import java.util.Scanner;

public class HamzasGrocery
{
// instance variables - replace the example below with your own
private Scanner in;

/**
 * Constructor for objects of class HamzasGrocery
 */
public HamzasGrocery()
{
    Scanner in = new Scanner(System.in);
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void sampleMethod()
{
double choice1;
double choice2;
double choice3;
double choice4;
double choice5;
double total;

System.out.print("Enter item #1: ");
System.out.println();
choice1 = in.nextDouble();
System.out.print("Enter item #2: ");
choice2 = in.nextDouble();
System.out.println();
System.out.print("Enter item #3: ");
choice3 = in.nextDouble();
System.out.println();
System.out.print("Enter item #4: ");
choice4 = in.nextDouble();
System.out.println();
System.out.print("Enter item #5: ");
choice5 = in.nextDouble();
System.out.println();

System.out.printf("%-10s", "Item #'s");
System.out.printf("%-10s", "Cost:");
System.out.printf("%-10s", "Total:");

}

}

user1533012
  • 5
  • 1
  • 1
  • 3

2 Answers2

4

Get rid of the Scanner in the "Scanner in = new Scanner.." code in the constructor.

By doing the declaration the way it is right now, you're saying that the in belong to the local scope and thus ignores the instance variable in.

So the constructor should be:

public HamzasGrocery()
{
    in = new Scanner(System.in);
}
Mamsaac
  • 6,173
  • 3
  • 21
  • 30
1

In your constructor, you are initializing a new Scanner, not your instance variable Scanner. try this:

public HamzasGrocery()
{
     in = new Scanner(System.in);
}
MikeB
  • 2,402
  • 1
  • 15
  • 24