我在项目中有以下课程:
Account对象需要Customer对象和期初余额。 Customer对象需要Name对象和Date对象。 Name对象需要字符串来表示名字和姓氏 我需要询问用户详细信息以创建名称和日期对象,以及期初余额。
我必须通过从用户那里获取相关信息来创建一个新帐户,即它要求用户键入客户的姓名,出生日期等。它读取用户的回复,创建帐户并将其添加到银行。
当我运行public void createNewAccount()方法时,我不断收到一条错误消息“java.lang.NullPointerException”。非常感谢任何帮助。提前致谢。
以下是我的班级类的源代码。
import java.util.ArrayList;
public class Bank
{
public static final double INTEREST_RATE = 0.012;//1.2%
// instance variables - replace the example below with your own
private ArrayList<Account> accounts;
private InputReader reader;
private Name fullName;
private Date dateOfBirth;
/**
* Constructor for objects of class Bank
*/
public Bank()
{
// initialise instance variables
}
/*
* Adds an existing Account to the bank
* @param account
*/
public void addAccount(Account account)
{
accounts.add(account);
}
public void createNewAccount() {
System.out.println("Please enter your first name: ");
String firstName = reader.readString();
System.out.println("Hello " + firstName + ". " + "What is your last name?");
String lastName = reader.readString();
System.out.println("Your last name is " + lastName);
System.out.println("Please enter your year of birth: ");
int thisYear = reader.readInt();
System.out.println("Please enter your month of birth: ");
int thisMonth = reader.readInt();
System.out.println("Please enter your date of birth: ");
int thisDay = reader.readInt();
Name theName = new Name(firstName, lastName);
Date theDateOfBirth = new Date(thisYear, thisMonth, thisDay);
}
}
答案 0 :(得分:1)
您必须先初始化阅读器,然后才能尝试阅读。
答案 1 :(得分:0)
Scanner scanner = new Scanner(System.in);
The scanner object has a lot of functions you can use;
答案 2 :(得分:0)
您的InputReader阅读器已声明,但未初始化,因此为NullPointerExceptin。将其更改为更常用的:
Scanner scanner = new Scanner(System.in);
然后你可以使用它的方法进行用户输入:
scanner.nextLine() for strings
scanner.nextInt() for ints
scanner.nextDouble() for doubles
等
检查文档here。
答案 3 :(得分:0)
您可以使用扫描仪更换阅读器。这样的事情。
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first name: ");
String firstName = scan.next();
System.out.println("Hello " + firstName + ". " + "What is your last name?");
String lastName = scan.next();
System.out.println("Your last name is " + lastName);
System.out.println("Please enter your year of birth: ");
int thisYear = scan.nextInt();
System.out.println("Please enter your month of birth: ");
int thisMonth = scan.nextInt();
System.out.println("Please enter your date of birth: ");
int thisDay = scan.nextInt();
//Then do what you are supposed to do......
答案 4 :(得分:0)
您需要初始化实例变量:
public class Bank
{
public static final double INTEREST_RATE = 0.012;
private ArrayList<Account> accounts;
private InputReader reader;
private Name fullName;
private Date dateOfBirth;
public Bank()
{
// initialise instance variables <- where it says to
accounts = new ArrayList<Account>();
reader = new InputReader();
...
}
InputReader必须是赋值包的一部分,所以我不知道它的构造函数是什么。