目标是为ATM对象创建帐户注册方法。但我一直打破用于进入循环的if语句。我认为我的“措辞”是关闭的,但我在如何解决这个问题上留下了空白。有什么建议?问题本身位于if(acc[i].getAcc()==0)
,其中.getAcc
是类中的getter。
package atmassignment;
import java.util.Scanner;
public class AtmAssignment {
static Scanner in = new Scanner(System.in);
static int cou = 1;
static Account[] acc = new Account[10];
public static void main(String[] args) {
menu();
}
public static void menu(){
char opt;
System.out.println("Thanks for accessing ATManager.");
System.out.println("Please select a menu option to proceed.");
System.out.println("1-Register a new account, 2-Access an account, 0-Exit ATManager");
opt = in.next().charAt(0);
switch (opt) {
case '1':
newAccount();
break;
case '2':
selAccount();
break;
case '0':
System.out.println("Goodbye.");
break;
default:
System.out.println("Invalid Entry.");
break;
}
}
public static void newAccount(){
System.out.println("Account registration");
for (int i = 0; i < acc.length; i++){
if(acc[i].getAcc()==0){
System.out.println("Please enter your first name...");
String fn = in.next();
System.out.println("Please enter your last name...");
String ln = in.next();
System.out.println("Please enter your address...");
String ad = in.next();
System.out.println("Please provide a contact number...");
String cn = in.next();
Customer cus = new Customer(fn, ln,ad,cn);
System.out.println("What is your starting balance...");
double bal = in.nextDouble();
acc[i] = new Account(cou, bal, cus);
System.out.println("Your account is registered as ID#"+cou);
break;
} else {
System.out.println("Sorry, no more accounts can be created.");
break;
}
}
}
}
答案 0 :(得分:1)
这会分配一个对象引用数组:
static Account[] acc = new Account[10];
但是它实际上并没有分配任何对象,因此当您尝试访问第一个元素时,可能会获得空指针异常。在您的初始化代码中,执行以下操作:
for(int i = 0; i < 10; i++)
acc[i] = new Account();
答案 1 :(得分:1)
在实际构建对象之前调用acc[i].getAcc()==0
。也许修改for循环以便创建对象,然后使用setter方法收集输入并更新对象?这当然要求您为Account类提供某种默认构造函数。
acc[j through maxLength] = new Account(); //where j spans the entire length of the array
for (int i = 0; i < acc.length; i++){
if(acc[i].getAcc()==0){
System.out.println("Please enter your first name...");
String fn = in.next();
System.out.println("Please enter your last name...");
String ln = in.next();
System.out.println("Please enter your address...");
String ad = in.next();
System.out.println("Please provide a contact number...");
String cn = in.next();
Customer cus = new Customer(fn, ln,ad,cn);
System.out.println("What is your starting balance...");
double bal = in.nextDouble();
acc[i].setContact(###);
acc[i].setBalance(###); //ETC
System.out.println("Your account is registered as ID#"+cou);
break;
} else {
System.out.println("Sorry, no more accounts can be created.");
break;
}
}
答案 2 :(得分:0)
可能您没有填充您的Account []数组。在这里,我只能看到你声明你的数组 -
static Account[] acc = new Account[10];
所以在那之后,当你试图使用for循环获取数组元素时,你无法访问它们。您在if(acc[i].getAcc()==0)
这一行收到错误。因此,我建议您删除if if,因为您在此行后面填写了帐户 - acc[i] = new Account(cou, bal, cus);
希望它会有所帮助 非常感谢。