gpt4 book ai didi

java - 不断收到 java.lang.nullException : null 的错误

转载 作者:行者123 更新时间:2023-12-01 17:29:07 24 4
gpt4 key购买 nike

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

}

}

最佳答案

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

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

所以构造函数应该是:

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

关于java - 不断收到 java.lang.nullException : null 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12719398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com