无法执行Login方法.感觉填充数组的对象创建有问题:非常感谢您的帮助



尝试创建一个银行管理应用程序。创建新用户后无法执行Login方法。感觉填充Perons和Account数组的对象创建有问题。请帮忙。

/用于保存帐户详细信息的帐户类/

public class Account extends Persons {
int accountNum;
int pin;
float checkingBal;
float savingBal;
float withDrawAmount;
float depositAmmount;
float transferAmount;
public  Account(){ }
public Account(int accountNum, float checkingBal, float savingBal, int pin ){
this.accountNum = accountNum;
this.checkingBal = checkingBal;
this.savingBal = savingBal;
this.pin = pin;
}
public void setAccountNum(int accountNum){
this.accountNum = accountNum;
}
public void setPin(int pin){
this.pin = pin;
}
public int getAccountNum(){
return accountNum;
}
public int getPin(){
return pin;
}

public void withDraw(float withDrawAmount){
this.savingBal = this.savingBal - withDrawAmount;
}
public void deposit(float depositAmmount){
this.checkingBal = this.checkingBal + depositAmmount;
}
public void transfer(float transferAmount, String fromAccount, String toAccount){
if(fromAccount == "Checking" && toAccount == "Savings"){
this.checkingBal = this.checkingBal - transferAmount;
this.savingBal = this.savingBal + transferAmount;
}else if(fromAccount == "Savings" && toAccount == "Checking"){
this.savingBal = this.savingBal - transferAmount;
this.checkingBal = this.checkingBal + transferAmount;
}
System.out.print("Your New Checking Balance Is: "+this.checkingBal);
System.out.print("Your New Savings Balance Is: "+this.savingBal);
}
public float checkBalance(int accountNum){
float totalBalance = 0;
if(this.accountNum == accountNum){
totalBalance = this.checkingBal + this.savingBal;
}
return totalBalance;
}
}
/*******************************************************************************************************/

/人员类容纳所有拥有帐户的人员/

import java.util.Date;
public class Persons {
String fname;
String lname;
int age;
String dob;
String address;
float yearlyIncome;
int accountNum;

public Persons(){}
public Persons(String fname, String lname, int age, String dob, String address, float yearlyIncome, int accountNum){
this.fname = fname;
this.lname = lname;
this.age = age;
this.dob = dob;
this.address = address;
this.yearlyIncome = yearlyIncome;
this.accountNum = accountNum;
}
public void setFname(String fname) {
this.fname = fname;
}
public void setLname(String lname) {
this.lname = lname;
}
public void setAge(int age) {
this.age = age;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(String address) {
this.address = address;
}
public void setYearlyIncome(float yearlyIncome) {
this.yearlyIncome = yearlyIncome;
}
public void setAccountNum(int accountNum){
this.accountNum = accountNum;
}
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
public int getAge() {
return age;
}
public String getDob() {
return dob;
}
public String getAddress() {
return address;
}
public float getYearlyIncome() {
return yearlyIncome;
}
public int getAccountNum(){
return accountNum;
}
}
/*****************************************************************************************************/

/Java主类/

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.Scanner;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Scanner scanf = new Scanner(System.in);
Persons people[] = new Persons[3];
Account personAccount[] = new Account[3];

float withdrawAmount;
float depositAmount;
float transferAmount;
int mainChoice;
int choice;
int counter = 0;
int userId = 0;
int loopBreak = 0;
int loginSuccess = -1;
while(loopBreak != -1){
System.out.println("================================================================================================");
System.out.println("Welcome To The California Bank :)");
System.out.println("1. Login..");
System.out.println("2. Create A New Customer.");
System.out.println("3. Done With Transactions.");

mainChoice = scanf.nextInt();
switch (mainChoice) {
case 1:
System.out.println("Please Enter Your Account Number:");
int accountNum = scanf.nextInt();
System.out.println("Please Enter Your Pin:");
int pin = scanf.nextInt();
for (int i = 0; i <= counter; i++) {
if (personAccount[i].getAccountNum() == accountNum && personAccount[i].getPin() == pin) {
System.out.println(personAccount[i].getAccountNum());
System.out.println(personAccount[i].getPin());
System.out.println("Customer Logged In and Validated.");
userId = i;
loginSuccess = 0;
} else {
System.out.println("Sorry You Are Not A Current Customer!");
loginSuccess = -1;
}
}
if(loginSuccess == 0){
System.out.println("======================================================================================");
System.out.println("What Else Would You Like To Do Today?");
System.out.println("1. Deposit.");
System.out.println("2. Withdraw.");
System.out.println("3. Transfer Money.");
System.out.println("4. Check Balance.");
choice = scanf.nextInt();
switch (choice) {
case 1:
System.out.println("How Much Money Would You Like To Deposit?");
depositAmount = scanf.nextFloat();
personAccount[userId].deposit(depositAmount);
break;
case 2:
System.out.println("How Much Money Would You Like To Withdraw Today?");
withdrawAmount = scanf.nextFloat();
personAccount[userId].withDraw(withdrawAmount);
break;
case 3:
System.out.println("How Much Money Would You Like To Withdraw Today?");
transferAmount = scanf.nextFloat();
System.out.println("1. Press 1 To Transfer From Checking to Savings.");
System.out.println("2. Press 2 To Transfer From Savings To Checking.");
int transferChoice;
transferChoice = scanf.nextInt();
if (transferChoice == 1) {
personAccount[userId].transfer(transferAmount, "Checking", "Savings");
} else {
personAccount[userId].transfer(transferAmount, "Savings", "Checking");
}
case 4:
System.out.println("Here Is Your Total Account Balance");
personAccount[userId].checkBalance(people[counter].accountNum);
break;
}
}
break;
case 2:
people[counter] = new Persons();
personAccount[counter] = new Account();
System.out.println("Please Enter Your First Name For The Account Creation:");
scanf.next();
String fName = scanf.nextLine();
System.out.println("Please Enter Your Last Name For The Account Creation:");
scanf.next();
String lName = scanf.nextLine();
people[counter].setFname(fName);
people[counter].setLname(lName);
System.out.println("Please Enter Your Age:");
int age = scanf.nextInt();
people[counter].setAge(age);
System.out.println("Please Enter Your Date Of Birth:");
String dob = scanf.next();
people[counter].setDob(dob);
System.out.println("Please Enter Your Address:");
scanf.next();
String address = scanf.nextLine();
people[counter].setAddress(address);
System.out.println("Please Enter Your Yearly Income:");
float annualIncome = scanf.nextFloat();
people[counter].setYearlyIncome(annualIncome);
System.out.println("Generating Your Account Number.....");
Random rand = new Random();
accountNum = rand.nextInt(100000);
people[counter].setAccountNum(accountNum);
personAccount[counter].setAccountNum(accountNum);
System.out.println("Your New Account Number Is: "+accountNum);
System.out.println("Please Enter A 4 Digit Pin");
pin = scanf.nextInt();
personAccount[counter].setPin(pin);
System.out.println("New Customer Created:");
counter++;
break;
case 3:
System.out.println("Thanks For Using The California Banking System. Goodbye!");
loopBreak = -1;
break;
}
}
}
}

以下是我在创建用户后得到的错误:

  1. 登录
  2. 创建新客户
  3. 事务处理完毕。1.请输入您的账号:90806请输入您的密码:3333908063333客户已登录并验证。线程中的异常";主";java.lang.NullPointerException:无法调用"Account.getAccountNum(("因为";personAccount[i]";为null在Main.Main(Main.java:48(

关于您的代码有很多东西,但首先是关于您的错误NullPointerException的解释。

例如,当您尝试对null元素调用某些方法时,会引发此异常。在您的案例中,您将数组声明为3个元素,并且只添加一个Account(新创建的(。然后迭代具有null元素的数组(第二个和第三个为null(。您应该去掉这个for循环,或者将数组初始化为1个元素大小=新帐户[1],然后每次将您的新帐户复制到更大大小的新数组。但这将是一个糟糕的解决方案。另一种方式(更好的

数组的大小不是动态的,因此您应该使用其中一个集合https://www.javatpoint.com/collections-in-java例如List(ArrayList就足够了(。我将向你展示如何改进你的代码,希望你能从中学到一些东西。

好的,这是代码:

Person(不是Person,不应该是(,不要用float来表示金钱,使用BigDecimal,将您的字段标记为私有或受保护(阅读封装(,更好地描述您的字段,而不是像dob-write dateOfBirth,我在这里使用LocalDate,不要使用旧的Time api,更好地查看新的Java Time api,还可以通过:currentDate-dateOfBirth来计算用户年龄

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Person {
private String firstName;
private String lastName;
private int age;
private LocalDate dateOfBirth;
private String address;
private BigDecimal yearlyIncome;
private int accountNumber;
public Person() { }
public Person(String firstName, String lastName, int age, LocalDate dateOfBirth, String address, BigDecimal yearlyIncome, int accountNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.dateOfBirth = dateOfBirth;
this.address = address;
this.yearlyIncome = yearlyIncome;
this.accountNumber = accountNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public BigDecimal getYearlyIncome() {
return yearlyIncome;
}
public void setYearlyIncome(BigDecimal yearlyIncome) {
this.yearlyIncome = yearlyIncome;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
}

好的,下一个帐户您应该阅读有关super((关键字从父类调用方法或构造函数的信息,我在这里使用它只是为了向您展示如何做到这一点,您可以将它提供给父类和设置帐户类字段

import java.math.BigDecimal;
public class Account extends Person {
private int accountNumber;
private int pin;
private BigDecimal checkingBalance = BigDecimal.ZERO;
private BigDecimal savingBalance = BigDecimal.ZERO;
public Account() { }
public Account(int accountNumber, int pin, BigDecimal checkingBalance, BigDecimal savingBalance){
this.accountNumber = accountNumber;
this.checkingBalance = checkingBalance;
this.savingBalance = savingBalance;
this.pin = pin;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public int getPin() {
return pin;
}
public void setPin(int pin) {
this.pin = pin;
}
public void withDraw(BigDecimal withDrawAmount){
this.savingBalance = this.savingBalance.subtract(withDrawAmount);
}
public void deposit(BigDecimal depositAmmount){
this.checkingBalance = this.checkingBalance.subtract(depositAmmount);
}
public void transfer(BigDecimal transferAmount, String fromAccount, String toAccount){
if(fromAccount.equals("Checking") && toAccount.equals("Savings")){
this.checkingBalance = this.checkingBalance.subtract(transferAmount);
this.savingBalance = this.savingBalance.add(transferAmount);
}else if(fromAccount.equals("Savings") && toAccount.equals("Checking")){
this.savingBalance = this.savingBalance.subtract(transferAmount);
this.checkingBalance = this.checkingBalance.add(transferAmount);
}
System.out.print("Your New Checking Balance Is: " + this.checkingBalance);
System.out.print("Your New Savings Balance Is: " + this.savingBalance);
}
public BigDecimal checkBalance(){
return this.checkingBalance.add(this.savingBalance);
}
}

我改进了一点Main类,你可以看到我使用List personsAccount,集合是动态的,你可以添加你想要的任意多的元素,这意味着你使用account类型的集合,你也可以像List一样做,但首先要了解继承和泛型。我在主菜单后面添加了第五个选项,也使用了do while选项,1个列表就足够了,你不需要人员和帐户数组。

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main {
private static final Scanner scanner = new Scanner(System.in);
//if you use java 8 or above you can just do it like = new ArrayList<>();
//static is here just because of example, you should reconsider it
private static final List<Account> personsAccounts = new ArrayList<Account>();
public static void main(String[] args) {
BigDecimal withdrawAmount;
BigDecimal depositAmount;
BigDecimal transferAmount;
int mainChoice;
int choice;
boolean session = true;
Account currentLoggedAccount = new Account();
int loginSuccess = -1;
while (session) {
System.out.println("================================================================================================");
System.out.println("Welcome To The California Bank :)");
System.out.println("1. Login..");
System.out.println("2. Create A New Customer.");
System.out.println("3. Done With Transactions.");
mainChoice = scanner.nextInt();
switch (mainChoice) {
case 1:
System.out.println("Please Enter Your Account Number:");
int accountNumber = scanner.nextInt();
System.out.println("Please Enter Your Pin:");
int pin = scanner.nextInt();
for (int i = 0; i < personsAccounts.size(); i++) {
if (personsAccounts.get(i).getAccountNumber() == accountNumber && personsAccounts.get(i).getPin() == pin) {
System.out.println(personsAccounts.get(i).getAccountNumber());
System.out.println(personsAccounts.get(i).getPin());
System.out.println("Customer Logged In and Validated.");
currentLoggedAccount = personsAccounts.get(i);
loginSuccess = 0;
} else {
System.out.println("Sorry You Are Not A Current Customer!");
loginSuccess = -1;
}
}
if (loginSuccess == 0) {
do {
System.out.println("======================================================================================");
System.out.println("What Else Would You Like To Do Today?");
System.out.println("1. Deposit.");
System.out.println("2. Withdraw.");
System.out.println("3. Transfer Money.");
System.out.println("4. Check Balance.");
System.out.println("5. Back to main menu");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("How Much Money Would You Like To Deposit?");
depositAmount = scanner.nextBigDecimal();
currentLoggedAccount.deposit(depositAmount);
break;
// is case 2 and 3 is the same?
case 2:
System.out.println("How Much Money Would You Like To Withdraw Today?");
withdrawAmount = scanner.nextBigDecimal();
currentLoggedAccount.withDraw(withdrawAmount);
break;
case 3:
System.out.println("How Much Money Would You Like To Withdraw Today?");
transferAmount = scanner.nextBigDecimal();
System.out.println("1. Press 1 To Transfer From Checking to Savings.");
System.out.println("2. Press 2 To Transfer From Savings To Checking.");
int transferChoice;
transferChoice = scanner.nextInt();
if (transferChoice == 1) {
currentLoggedAccount.transfer(transferAmount, "Checking", "Savings");
} else {
currentLoggedAccount.transfer(transferAmount, "Savings", "Checking");
}
break;
case 4:
System.out.println("Here Is Your Total Account Balance");
currentLoggedAccount.checkBalance();
break;
default:
System.out.println("There is no option :(");
break;
}
}
while (choice != 5);
}
break;
case 2:
Account accountToAdd = new Account();
System.out.println("Please Enter Your First Name For The Account Creation:");
scanner.next();
String firstName = scanner.nextLine();
accountToAdd.setFirstName(firstName);
System.out.println("Please Enter Your Last Name For The Account Creation:");
scanner.next();
String lastName = scanner.nextLine();
accountToAdd.setLastName(lastName);
System.out.println("Please Enter Your Age:");
int age = scanner.nextInt();
accountToAdd.setAge(age);
System.out.println("Please Enter Your Date Of Birth:");
String date = scanner.next();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy");
accountToAdd.setDateOfBirth(LocalDate.parse(date, dtf));
System.out.println("Please Enter Your Address:");
scanner.next();
String address = scanner.nextLine();
accountToAdd.setAddress(address);
System.out.println("Please Enter Your Yearly Income:");
BigDecimal annualIncome = scanner.nextBigDecimal();
accountToAdd.setYearlyIncome(annualIncome);
System.out.println("Generating Your Account Number.....");
Random rand = new Random();
//that is some kind of weir because what if somebody have this number yet? :D
int newAccountNumber = rand.nextInt(100000);
accountToAdd.setAccountNumber(newAccountNumber);
System.out.println("Your New Account Number Is: " + newAccountNumber);
System.out.println("Please Enter A 4 Digit Pin");
pin = scanner.nextInt();
accountToAdd.setPin(pin);
//adding new account to list
personsAccounts.add(accountToAdd);
System.out.println("New Customer Created:");
break;
case 3:
System.out.println("Thanks For Using The California Banking System. Goodbye!");
session = false;
break;
default:
System.out.println("There is no option :(");
break;
}
}
}
}

这段代码并不完美,但它很有效,而且更清晰,你可以根据自己的意愿进行改进。希望你能学到一些东西,读一下java。集合,java。时间,java泛型,你也可以为每个循环交换普通的for,比如for(Account Account:perssAccounts({}。干杯

最新更新