继续得到java.lang.nullexception的错误:null

时间:2012-10-04 02:07:18

标签: java input argumentnullexception

我正在处理的代码旨在接受来自用户的输入,但每当我运行程序时,它一直告诉我有一个错误,java.land.nullexception:null。我不知道该怎么做!

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:");

}

}

2 个答案:

答案 0 :(得分:4)

在构造函数中的“Scanner in = new Scanner ..”代码中删除扫描程序。

通过现在的方式进行声明,你说的是in属于本地范围,因此忽略了实例变量。

所以构造函数应该是:

public HamzasGrocery()
{
    in = new Scanner(System.in);
}

答案 1 :(得分:1)

在构造函数中,您正在初始化一个新的Scanner,而不是您的实例变量Scanner。试试这个:

public HamzasGrocery()
{
     in = new Scanner(System.in);
}