30/09/2018, 19:30

Lỗi ngoại lệ trong JAVA

Xin mọi người xem hộ em với không hiểu sao lại có lỗi này ạ
Em có 2 class
package samsung.java.week2.bank;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class SavingAccount {
// tien goc
private double principalAmount;
// ngay bat dau gui
private Date depositDate;
//thoi gian bat dau rut
private long withdrawal;
// lai suat theo %
private double interestRate;
// so tai khoan
private int accountNumber;
// ten tai khoan
private String accountName;
Scanner enter = new Scanner(System.in);

public int getAccountNumber() {
	return accountNumber;
}

public void setAccountNumber(int accountNumber) {
	this.accountNumber = accountNumber;
}

public String getAccountName() {
	return accountName;
}

public void setAccountName(String accountName) {
	this.accountName = accountName;
}

public double getPrincipalAmount() {
	return principalAmount;
}

public void setPrincipalAmount(double principalAmount) {
	this.principalAmount = principalAmount;
}

public Date getDepositDate() {
	return depositDate;
}

public void setDepositDate(Date depositDate) {
	this.depositDate = depositDate;
}

public double getInterestRate() {
	return interestRate;
}

public void setInterestRate(double interestRate) {
	this.interestRate = interestRate;
}
public long getWithdrawal() {
	return withdrawal;
}

public void setWithdrawal(long withdrawal) {
	this.withdrawal = withdrawal;
}

// khoi tao mac dinh khong tham so
public SavingAccount() {
	setAccountNumber(01234567);
	setAccountName("abcd");
}

// calculate interest
// Tinh tien lai
public double calculateInterest() {

	double interest = getPrincipalAmount() * getInterestRate() * ((getWithdrawal()  - getDepositDate().getTime()) / 86400000);
	return interest;
}

// phuong thuc rut tien lai
public void withdrawalInterest() {
	System.out.println("Interest :" + calculateInterest());
	// get current date time with Date()
	Date date = new Date();
	setDepositDate(date);
}


// rut tien lai va mot phan tien goc (interest and partial withdrawals
// principals)
public void interestAndPWP() {
	System.out.println("Enter principal amount need withdraw : ");
	double principalWithdraw = enter.nextDouble();
	do {
		if (principalWithdraw <= 0) {
			System.out.println("principalWithdraw > 0. Please enter again.");
		} else {
			setPrincipalAmount(getPrincipalAmount() - principalWithdraw);
			System.out.println("principal Withdraw : " + principalWithdraw);
			withdrawalInterest();
		}
	} while (principalWithdraw <= 0);
}
//nhap ngay rut
public void withdrawalDate(){
	System.out.print("Plase enter withdrawal date (dd/MM/yyyy) :");
	String expectedPattern = "dd/MM/yyyy";
	SimpleDateFormat formatter = new SimpleDateFormat(expectedPattern);
	try
	{
	// (2) give the formatter a String that matches the
	//SimpleDateFormat pattern
	String userInput = enter.nextLine();
	Date date = formatter.parse(userInput);
	setWithdrawal(date.getTime());
	}catch (Exception e){
	// execution will come here if the String that is given
	// does not match the expected format.
	e.printStackTrace();
	}
}

// gui them tien vao tien goc
public void sendMoreMoney() {

	System.out.println("Please enter send more money : ");
	double sendMoreMoney = enter.nextDouble();
	if (getPrincipalAmount() != 0) {
		do {
			if (sendMoreMoney <= 0) {
				System.out.println("principalWithdraw > 0. Please enter again.");
			} else {
				setPrincipalAmount(getPrincipalAmount() + sendMoreMoney);
				withdrawalInterest();
				withdrawalDate();
			}
		} while (sendMoreMoney <= 0);
	}
	if (getPrincipalAmount() == 0) {
		do {
			if (sendMoreMoney <= 0) {
				System.out.println("principalWithdraw > 0. Please enter again.");
			} else {
				setPrincipalAmount(getPrincipalAmount() + sendMoreMoney);
				withdrawalDate();
			}
		} while (sendMoreMoney <= 0);
	}
}

// rut tat
public void withdrawalAll() {
	System.out.println("You withdrawal principal amount : " + getPrincipalAmount());
	withdrawalInterest();
	setPrincipalAmount(0);
}

}

và một class
package samsung.java.week2.bank;

import java.io.IOException;
import java.util.Scanner;

public class Communication {

private static SavingAccount[] account = new SavingAccount[50];
public static int i = 0;

// chuc nang tao acc va nhap lai suat
public static void appendNewAccount() {
	Scanner enter = new Scanner(System.in);
	System.out.println("Please, enter new account number (0-9): ");
	account[i].setAccountNumber(enter.nextInt());
	if (compare(i) == 1) {
		System.out.println("account number already exists ");
	}
	if (compare(i) != 1) {
		System.out.println("Please, enter new account name : ");
		account[i].setAccountName(enter.nextLine());
		System.out.println("Please, enter interest rate (%) : ");
		account[i].setInterestRate(enter.nextDouble());
		i++;
	}
	if (compare(i) == 0) {
		System.out.println("Please, enter new account name : ");
		account[i].setAccountName(enter.nextLine());
		System.out.println("Please, enter interest rate (%) : ");
		account[i].setInterestRate(enter.nextDouble());
		i++;
	}
}

// so sanh account trung so account number tra ve 1
public static int compare(int i) {
	int test = 0;
	if (i == 0) {
		test = 0;
	}
	if (i != 0) {
		for (int j = (i - 1); j >= 0; j--) {
			if ((account[i].getAccountNumber()) != (account[j].getAccountNumber())) {
				test = 0;
			} else {
				test = 1;
				// quit for
				break;
			}
		}
	}
	return test;
}

// test = 50 la khong co tai khoan. de la 50 de khi tra ve i chi co the <50
// search account number
public static int searchAccountNumber(int searchAccountNumber) {
	int test = 50;

	for (int j = 0; j <= i; j++) {
		if (searchAccountNumber == account[i].getAccountNumber()) {
			test = i;
			// quit for
			break;
		} else {
			test = 50;
		}
	}
	return test;
}

// chuc nang rut tien lai
public static void functionWithdrawalInterest() {
	Scanner enter = new Scanner(System.in);
	System.out.println("Please enter account number : ");
	int searchAccountNumber = enter.nextInt();
	if (searchAccountNumber(searchAccountNumber) != 50) {
		// gan k = so nay de the hien cac hoat dong duoi day la cua mot doi
		// tuong k
		// neu khong khi ta lam account[i] se la i cua tai khoan vua lap
		int k = searchAccountNumber(searchAccountNumber);
		account[k].withdrawalInterest();
	} else {
		System.out.println("account number not have!");
	}
}

// chuc nang rut goc mot phan
public static void functionInterestAndPWP() {
	Scanner enter = new Scanner(System.in);
	System.out.println("Please enter account number : ");
	int searchAccountNumber = enter.nextInt();
	if (searchAccountNumber(searchAccountNumber) != 50) {
		// gan k = so nay de the hien cac hoat dong duoi day la cua mot doi
		// tuong k
		// neu khong khi ta lam account[i] se la i cua tai khoan vua lap
		int k = searchAccountNumber(searchAccountNumber);
		account[k].interestAndPWP();
	} else {
		System.out.println("account number not have!");
	}
}

// chuc nang tat toan
public static void functionWithdrawalAll() {
	Scanner enter = new Scanner(System.in);
	System.out.println("Please enter account number : ");
	int searchAccountNumber = enter.nextInt();
	if (searchAccountNumber(searchAccountNumber) != 50) {
		// gan k = so nay de the hien cac hoat dong duoi day la cua mot doi
		// tuong k
		// neu khong khi ta lam account[i] se la i cua tai khoan vua lap
		int k = searchAccountNumber(searchAccountNumber);
		account[k].withdrawalAll();
	} else {
		System.out.println("account number not have!");
	}
}

// chuc nang gui tien
public static void functionSendMoreMoney() {
	Scanner enter = new Scanner(System.in);
	System.out.println("Please enter account number : ");
	int searchAccountNumber = enter.nextInt();
	if (searchAccountNumber(searchAccountNumber) != 50) {
		// gan k = so nay de the hien cac hoat dong duoi day la cua mot doi
		// tuong k
		// neu khong khi ta lam account[i] se la i cua tai khoan vua lap
		int k = searchAccountNumber(searchAccountNumber);
		account[k].sendMoreMoney();
	} else {
		System.out.println("account number not have!");
	}
}

// chuc nang xem thong tin
public static void showAccount() {
	Scanner enter = new Scanner(System.in);
	System.out.println("Please enter account number : ");
	int searchAccountNumber = enter.nextInt();
	if (searchAccountNumber(searchAccountNumber) != 50) {
		// gan k = so nay de the hien cac hoat dong duoi day la cua mot doi
		// tuong k.
		// neu khong khi ta lam account[i] se la i cua tai khoan vua lap
		int k = searchAccountNumber(searchAccountNumber);
		System.out.println("Account Number :" + account[k].getAccountNumber());
		System.out.println("Account Name :" + account[k].getAccountName());
		System.out.println("Principal amount :" + account[k].getPrincipalAmount());
		System.out.println("Interest :" + account[k].calculateInterest());
	} else {
		System.out.println("account number not have!");
	}
}

// show menu
public static void showMenu() {
	System.out.println("	Bank Management System");
	System.out.println("------------------------------");
	System.out.println("1. Append new account");
	System.out.println("2. Withdraw interest");
	System.out.println("3. Partialy withdraw ");
	System.out.println("4. Totally withdraw");
	System.out.println("5. Deposit");
	System.out.println("6. Display information");
	System.out.println("Your choice (1-6, other to quit): ");
}

public static void main(String[] args) {
	showMenu();
	Scanner enter = new Scanner(System.in);
	String choice = enter.nextLine();
	int next = 0;
	do {
		switch (choice) {
		case "1":
			appendNewAccount();
			break;
		case "2":
			functionWithdrawalInterest();
			break;
		case "3":
			functionInterestAndPWP();
			break;
		case "4":
			functionWithdrawalAll();
			break;
		case "5":
			functionSendMoreMoney();
			break;
		case "6":
			showAccount();
			break;
		default:
			System.out.println("you are quit!");
		}
		// Enter "Enter" show again the menu.
		System.out.println("Press Enter to continue...");
		try {
			next = System.in.read();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String trash = enter.nextLine();
	} while (next == 13);
}

}

Khi em chạy chọn 1 và nhập vào một số vd: 123 thì nó báo ngoại lệ

Bank Management System

  1. Append new account
  2. Withdraw interest
  3. Partialy withdraw
  4. Totally withdraw
  5. Deposit
  6. Display information
    Your choice (1-6, other to quit):
    1
    Please, enter new account number (0-9):
    123
    Exception in thread “main” java.lang.NullPointerException
    at samsung.java.week2.bank.Communication.appendNewAccount(Communication.java:15)
    at samsung.java.week2.bank.Communication.main(Communication.java:176)

Em nghĩ nó là cái này lỗi: account[i].setAccountNumber(enter.nextInt());
nhưng không hiểu sai ở đâu.
Xin mọi người mách em xử lý với ạ.
Em xin cảm ơn.

Con Gà Con viết 21:35 ngày 30/09/2018

Lỗi này đơn giản thui. Bạn chỉ tạo ra cái mảng 50 SavingAccount mà với mỗi phần tử trong mảng bạn chưa khởi tạo hay nói cách khác account[i] = null; mà đối tượng bị null thì bạn setAccountNumber(enter.nextInt()); thì làm sao được. Bạn nên khởi tạo đối tượng trước khi thao tác với nó.
Hy vọng giúp được bạn!

Bài liên quan
0