Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我得到了一个nullPointerException,我不明白为什么_Java_Arrays_Inheritance_Nullpointerexception_Polymorphism - Fatal编程技术网

Java 我得到了一个nullPointerException,我不明白为什么

Java 我得到了一个nullPointerException,我不明白为什么,java,arrays,inheritance,nullpointerexception,polymorphism,Java,Arrays,Inheritance,Nullpointerexception,Polymorphism,在我的会计课上 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.NumberFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calend

在我的会计课上

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.text.NumberFormat;
    import java.text.ParsePosition;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.util.Locale;

    public class Bankaccount implements java.io.Serializable {

private int ID;
private double amt;
private int firstdate;
private int seconddate;
private Calendar cal1 = new GregorianCalendar();
private Calendar cal2 = new GregorianCalendar();
private boolean dateflag = false;
private double rate;
private Checking checking;
private Savings savings;
private boolean accountType;

public Bankaccount() {
}

public Bankaccount(int ID, double amt) {
    this.ID = ID;
    this.amt = amt;
}

public String getBalance(double balance) {

    NumberFormat currencyFormatter = null;
    String currencyOut;

    currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
    currencyOut = currencyFormatter.format(balance);

    return currencyOut;

}

// This method prompts the user for the deposit and then adds it to the
// balance field.
public void deposit(boolean chsv) throws IOException {
    BufferedReader br;
    String entered_amount;
    boolean accountType = chsv;

    System.out.print("How much would you like to deposit? :");
    br = new BufferedReader(new InputStreamReader(System.in));
    entered_amount = br.readLine();
    double amount = Double.valueOf(entered_amount).doubleValue();
   if(accountType==true){

    double balance = getCheckingBalance();
    balance = balance + amount;
    setCheckingBalance(balance);
   } else{

    double balance = getSavingsBalance();
    balance = balance + amount;
    setSavingsBalance(balance);
   }

    if (accountType == true) {
        System.out.println("Your checking balance is: " + getCheckingBalance());
    } else {
        System.out.println("Your savings balance is: " + getSavingsBalance());


}
}

// This method prompts the user for the withdraw amount and then subtracts
// it from the balance field.
public void withdraw(boolean chsv) throws IOException {
    boolean accountType;
    accountType = chsv;
    BufferedReader br;
    String entered_amount;

    System.out.print("How much would you like to withdraw? :");
    br = new BufferedReader(new InputStreamReader(System.in));
    entered_amount = br.readLine();
    double amount = Double.valueOf(entered_amount).doubleValue();
    if (accountType == true) {
        if (getCheckingBalance() < amount) {
            System.out.println("Insufficient funds.");
        } else {
            double balance = getCheckingBalance();
            balance = balance - amount;
            setCheckingBalance(balance);
        }
    } else {
        if (getSavingsBalance() < amount) {
            System.out.println("Insufficient funds.");
        } else {
            double balance = getSavingsBalance();
            balance = balance - amount;
            setSavingsBalance(balance);
        }
    }
    if (accountType == true) {
        System.out.println("Your balance is: " + getCheckingBalance());
    } else {
        System.out.println("Your balance is: " + getSavingsBalance());

    }
}

// This function is only called on the first transaction after the
// account has been initialized to set the first time a transaction
// occurs for the account for the current year.
public void getDate1() throws IOException {

    System.out.print("Enter todays date(mm/dd/yyyy): ");
    BufferedReader br;
    br = new BufferedReader(new InputStreamReader(System.in));
    String inputText = br.readLine();
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    ParsePosition pos = new ParsePosition(0);
    //Date date= new Date();
    Date date = formatter.parse(inputText, pos);

    cal1.setTime(date);

    firstdate = cal1.get(cal1.DAY_OF_YEAR);
    dateflag = true;

}

// This method is called for every date entered after the first date.
// The previous second date is passed to the first date to keep track of
// time.
public void getDate2() throws IOException {

    System.out.print("Enter todays date(mm/dd/yyyy): ");
    BufferedReader br;
    br = new BufferedReader(new InputStreamReader(System.in));
    String inputText = br.readLine();
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    ParsePosition pos = new ParsePosition(0);
    Date date = new Date();
    date = formatter.parse(inputText, pos);

    cal2.setTime(date);

    seconddate = cal2.get(cal2.DAY_OF_YEAR);

    if (firstdate > seconddate) {
        System.out.println("You must enter a future date.");
        getDate2();
    }

}

// This method calulates the interest based on the previous date and the
// current date
public void getInterest(boolean chsv) {
    boolean accountType;
    accountType = chsv;
    int datediff = seconddate - firstdate;       
    rate = .05 / 365;
    double ratetime = Math.pow(1 + rate, datediff);
   if (accountType==true){
     double balance = getCheckingBalance();
    balance = balance * ratetime;
    setCheckingBalance(balance);
    firstdate = seconddate;
   }else {
       double balance = getSavingsBalance();
    balance = balance * ratetime;
    setSavingsBalance(balance);
    firstdate = seconddate;
   }

}

/**
 * @return the ID
 */
public int getID() {
    return ID;
}

/**
 * @param ID the ID to set
 */
public void setID(int ID) {
    this.ID = ID;
}

/**
 * @return the amt
 */
public double getAmt() {
    return amt;
}

/**
 * @param amt the amt to set
 */
public void setAmt(double amt) {
    this.amt = amt;
}

public void setCheckingBalance(double balance) {
    checking.setBalance(balance);
}

public double getCheckingBalance() {
    return checking.getBalance();
}

public void setSavingsBalance(double balance) {
    savings.setBalance(balance);
}

public double getSavingsBalance() {
    return savings.getBalance();
}

public String accountWord(boolean accountType) {
    boolean x = accountType;
    String s = "savings";
    if (x == true) {
        return "checking";
    } else if (x == false) {
        return "savings";
    }
    return null;
}

/**
 * @return the accountType
 */
public boolean isAccountType() {
    return accountType;
}

/**
 * @param accountType the accountType to set
 */
public void setAccountType(boolean accountType) {
    this.accountType = accountType;
}
第2行是它抛出空指针异常的地方,baArray是我的银行类的一个对象,如下所示。我还有一个支票和储蓄类,它扩展了我的Bankaccount类,如果你看看我的银行类的最底层,我正在使用这些方法来设置这些类中包含的余额值

这是我的主课

包edu.umsl

    import java.io.*;
    import java.util.*;
    import java.text.*;


private double balance;
private Bankaccount baArray[];
private int accountid;
public int arrayId;
public boolean accountType;

// Initial Constructor
// Once called the Account1 constructor presents a menu for users to make
// a deposit, withdrawal, check balance or exit.
// The menu is a loop that based on the selection will call either the
// deposit method, withdrawal method or exit the program.
public Account(double begin_balance) {
    balance = begin_balance;

} // End Initial Constructor

public void accountCheck() throws IOException {
    String yesno;
    int oldaccount;
    int newaccount;
    loadAccounts();
    System.out.println("Welcome to RIPOFF Bank, do you have an account with us? (yes or no)");
    yesno = KbdInput.readString();
    if (yesno.equalsIgnoreCase("yes")) {
        System.out.println("Please enter your account ID:");
        oldaccount = KbdInput.readInt();

        accountid = oldaccount;
        for (arrayId = 0; arrayId <= 2; arrayId++) {
            if (baArray[arrayId].getID() == accountid) {
                break;
            }
        }
    } else if (yesno.equalsIgnoreCase("no")) {
        System.out.println("Please choose an account id(integers only):");
        newaccount = KbdInput.readInt();
        accountid = newaccount;
        for (arrayId = 0; arrayId <= 2; arrayId++) {

            if (baArray[arrayId] == null) {
                baArray[arrayId] = new Bankaccount();
                baArray[arrayId].setID(accountid);

            }
            if (baArray[arrayId].getID() == accountid) {

                saveAccount();
                break;
            }
        }
    }
}

public void menu() throws IOException {
    System.out.println("Today you are opening an account, please enter the date");
    baArray[arrayId].getDate1();
    char mychar = 'z';
    while (mychar != 'e') {
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println("*********************************");
        System.out.println("*    WELCOME TO RIPUOFF BANK    *");
        System.out.println("*                               *");
        System.out.println("*     Come in and check out     *");
        System.out.println("*          our low 30%          *");
        System.out.println("*      interest rate loans      *");
        System.out.println("*                               *");
        System.out.println("*********************************");
        System.out.println();
        System.out.println("What would you like to do with your " + baArray[arrayId].accountWord(accountType) + " account (account# " + baArray[arrayId].getID() + "):");
        System.out.println("Deposit(d)");
        System.out.println("Withdraw(w)");
        System.out.println("CheckBalance(c)");
        System.out.println("Exit(e)");
        BufferedReader br;
        String input;
        int index = 0;
        br = new BufferedReader(new InputStreamReader(System.in));

        input = br.readLine();

        mychar = input.charAt(index);

        if (mychar == 'd' || mychar == 'D') {
            System.out.println("Your current balance in checking is:" + baArray[arrayId].getCheckingBalance());
            //if (dateflag == true)
            //{
            baArray[arrayId].getDate2();
            baArray[arrayId].getInterest(accountType);
            baArray[arrayId].deposit(accountType);
            //}

            //else
            //{
            //getDate1();
            //deposit();
            //}

        } else if (mychar == 'w' || mychar == 'W') {
            System.out.println("Your current balance is: " + baArray[arrayId].getCheckingBalance());
            //if (dateflag == true)
            //{
            baArray[arrayId].getDate2();
            baArray[arrayId].getInterest(accountType);
            baArray[arrayId].withdraw(accountType);
            //}
            //else
            //{
            //        getDate1();
            //        withdraw();
            //}
        } else if (mychar == 'c' || mychar == 'C') {
            if(accountType==true){
            System.out.println("Your current balance is: " + baArray[arrayId].getBalance(baArray[arrayId].getCheckingBalance()));
            }else{
                System.out.println("Your current balance is: " + baArray[arrayId].getBalance(baArray[arrayId].getSavingsBalance()));

            }
            }

    }
}

//Main method instantiates the initial account balance of 100 hundred dollars
//Then creates the account and lets the Account class take over from there.
public void loadAccounts() {
    try {
        FileInputStream inStream = new FileInputStream("file.out");
        ObjectInputStream is = new ObjectInputStream(inStream);
        baArray = (Bankaccount[]) is.readObject();
    } catch (Exception e) {
        baArray = new Bankaccount[3];
    }

}

public void saveAccount() {
    try {
        FileOutputStream outStream = new FileOutputStream("file.out");
        ObjectOutputStream os = new ObjectOutputStream(outStream);
        os.writeObject(baArray);
        os.flush();
        outStream.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

public static void main(String[] args) throws IOException {
    double init_amount = 100.00;
    Account ac = new Account(init_amount);

    ac.accountCheck();
   ac.accountType();
    ac.menu();
}
public void accountType(){

    System.out.println("Checking 1:");
    System.out.println("Savings 2:");
    System.out.println("Please select one of your accounts");
    int input = KbdInput.readInt();
    if(input==1){
        accountType = true;
        baArray[arrayId].setAccountType(accountType);
    }else if(input==2){
        accountType = false;
        baArray[arrayId].setAccountType(accountType);
    }else{
        System.out.println("Invalid Input");
    }

Java结果:1

通常这种错误是由于您创建了一个对象数组,但没有在数组中创建项。解决方案是在尝试使用数组之前用对象填充数组

例如,假设您有如下代码:

BankAccount[] baArray = new BankAccount[3];
这将创建一个大小为3的BankAccount数组,但该数组只包含空引用。若要使用阵列,必须首先用对象填充阵列:

for (int i = 0; i < baArray.length; i++) {
  baArray[i] = new BankAccount();
}
编辑 关于您的最新代码帖子:

我看到你说出你班上的银行账户。您需要将其更改为BankAccount以符合Java标准。 如果您的代码进入catch块,实际上您创建了一个大小为3的数组,但忽略了用对象填充数组。这将导致您发布的NPE。 当函数

public void setCheckingBalance(double balance) {
    checking.setBalance(balance);
}

运行时,将checking instance设置为null。

我没有看到任何声明或初始化baArray变量的代码。你可能想展示这个。试着阅读一些关于调试Java的内容。这太琐碎了,甚至不能问。@hovercraftfullofels我已经在我的edit@user2733862:请参阅编辑以回答。我已在最后一个代码块中添加了代码,如果您查看它将数组分配给object@user2733862:1什么支票帐户方法?我们不是说把数组分配给任何东西,而是说把对象放到数组项中。还考虑使用调试器来检查程序流和程序运行时的状态。1对不起,我在帐号的最后一个代码块的顶部进行了检查。在那里你会看到我有一个for循环,其中baArray[arrayId]=新银行账户;
public void setCheckingBalance(double balance) {
    checking.setBalance(balance);
}