2015-12-13 7 views
-1

По какой-то причине я получаю сообщение об ошибке в этой программе, и я понятия не имею, что это значит. Я пробовал искать походы, но ничего не связано с моей проблемой. Это имеет какое-то отношение к исключению IOException? Кроме того, где хранится вход? В файле класса? Например: если бы я должен был ввести деньги в учетную запись, было бы сохранено введенное значение в другом файле, или тот факт, что я сделал массив из 30 учетных записей для двойного количества всех 30 объектов?Класс учетной записи Ошибка

Основной класс:

 import java.util.Scanner; 
import java.text.NumberFormat; 
public class Account2 
{ 
    public static void main(String[] args) 
    { 
    Scanner scan = new Scanner(System.in); 
    Account[] acct = new Account[30]; 
    System.out.println("Enter your account number (1-30): "); 
    int key = scan.nextInt() - 1; 
    int reset = 0; 
    while (reset == 0) 
    { 
     System.out.println("Enter W for withdrawl; D for deposit; X to escape"); 
     char choice = scan.next().charAt(0); 

     if (choice == 'W' || choice == 'w' || choice == 'D' || choice == 'd' || choice == 'x' || choice == 'X') 
     { 
     if (choice == 'W' || choice == 'w') 
     { 
      System.out.println("Enter amount to withdraw: "); 
      Double withdraw1 = scan.nextDouble(); 
      if (withdraw1 <= acct[key].getBalance()) 
      { 
      acct[key].withdraw(withdraw1); 
      System.out.println("User # " + key++ + " funds after withdraw: " + acct[key].getBalance() + "$"); 
      System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$"); 
      reset++; 
      } 
      else 
      System.out.println("Insufficient funds."); 
     } 

     if (choice == 'D' || choice == 'd') 
     { 
      System.out.println("Enter amount to deposit: "); 
      Double deposit1 = scan.nextDouble(); 
      if (deposit1 > 0) 
      { 
      acct[key].deposit(deposit1); 
      System.out.println("User # " + key++ + " funds after deposit: " + acct[key].getBalance() + "$"); 
      System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$"); 
      reset++; 
      } 
      else 
      System.out.println("Use the withdrawl feature to withdrawl money."); 

     } 
     if (choice == 'x' || choice == 'X') 
      System.out.println("Thank You for using this bank."); 
      reset++; 
     } 
     else 
     { 
      System.out.println("Invalid entry, please try again"); 
      reset = 0; 
     } 
    } 
    } 
} 

второго класса: сообщение

import java.text.NumberFormat; //links to Part2 

public class Account 
{ 
    private final double RATE = 0.03; //Interest is 3% 

    private long acctNumber; 
    private double balance; 
    private String name; 

    //Defines owner, account number, and initial balance. 
    public Account(String owner, long account, double initial) 
    { 
    name = owner; 
    acctNumber = account; 
    balance = initial; 
    } 

    //deposits a specified amount and returns new balance 
    public double deposit(double amount) 
    { 
    balance = balance + amount; 
    return balance; 
    } 

    //withdraws the specified amount from the account and applies the fee 
    //             + returns balance 
    public double withdraw(double amount) 
    { 
    int fee = 1; 
    balance = balance - amount - fee; 
    return balance; 
    } 

    //Adds interest to the account 
    public double addInterest() 
    { 
    balance += (balance * RATE); 
    return balance; 
    } 
    public double getBalance() 
    { 
    return balance; 
    } 

    //returns a one line description of the account as a string 
    public String toString() 
    { 

    NumberFormat fmt = NumberFormat.getCurrencyInstance(); 
    return acctNumber + "/t" + name + "/t" + fmt.format(balance); 
    } 
} 

Ошибка:

Enter your account number (1-30): 
5 
Enter W for withdrawl; D for deposit; X to escape 
d 
Enter amount to deposit: 
50 
Exception in thread "main" java.lang.NullPointerException 
     at Account2.main(Account2.java:40) 

ответ

0

Вы пытаетесь Acces индекс acct но массив пуст Account[] acct = new Account[30];

Сначала вы должны заполнить массив, попробуйте сначала создать учетную запись пользователя.

+0

Ох, хорошая идея. Я сделаю это, а также, что вы имеете в виду, что он пуст? Не является ли начальное значение объекта типа double всегда равным 0? – Submersed24

+0

@ Submersed24 Да, но здесь у вас есть массив объектов 'Account', а не' double'. Не забудьте принять ответ :) –

+0

Спасибо за помощь, и, заполнив массив, вы имеете в виду, создав цикл for, который устанавливает acc [0] -acc [29] вверх со значением 0? – Submersed24

Смежные вопросы