0

我正在处理的代码旨在接受用户的输入,但每当我运行程序时,它总是告诉我有一个错误,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:");

}

}

4

2 回答 2

4

去掉构造函数中“Scanner in = new Scanner..”代码中的Scanner。

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

所以构造函数应该是:

public HamzasGrocery()
{
    in = new Scanner(System.in);
}
于 2012-10-04T02:09:23.503 回答
1

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

public HamzasGrocery()
{
     in = new Scanner(System.in);
}
于 2012-10-04T02:10:16.200 回答