Home > OS >  Difficulty with displaying array data in java
Difficulty with displaying array data in java

Time:12-08

I am learning java by myself and using the book Java in Two Semesters by Quentin Charatan and Aaron Kans. I am currently reading the chapter on Classes and Objects and I am having difficulty solving the last part of an exercise question. I have basic knowledge of objects, classes and arrays. I have yet to read about collections I would be really grateful for some help here. Thanks in advance.

Ques: Design and implement a program that performs in the following way:

  1. When the program starts, two bank accounts are created, using names and numbers which are written into the code.
  2. The user is then asked to enter an account number, followed by an amount to deposit in that account.
  3. The balance of the appropriate account is then updated accordingly—or if an incorrect account number was entered a message to this effect is displayed.
  4. The user is then asked if he or she wishes to make more deposits.
  5. If the user answers does wish to make more deposits, the process continues.
  6. If the user does not wish to make more deposits, then details of both accounts (account number, account name and balance) are displayed

The authors have provided a BankAccount class file which I have to use to create the bank Accounts and the methods given in the class to deposit and get balance. I am providing the code of the my attempt here

import java.util.Scanner;
 
public class ProgEx4
{
public static void main(String[] args)
  {
      int choice;
      Scanner keyboard = new Scanner(System.in);
    do
    { // Create a MENU system for user to choose options 
      System.out.println();
      System.out.println("Welcome to Bank Accounts");
      System.out.println("MENU");
      System.out.println("[1] Deposit Amount");
      System.out.println("[2] Exit");
  
      // User can enter choice here
      System.out.print("What would you like to do today? : ");
      choice = keyboard.nextInt();
  
      // switch used to process choice entered by user
      switch(choice)
      {
        case 1: deposit(); // this will go to the deposit method 
                break;
        case 2: break;    // this will exit the program 
        default: System.out.println("Invalid Choice"); // if user enters an invalid choice this will allow another attempt at entering choice
                 System.out.print("Please enter a option ( 1 or 2): ");
                 choice = keyboard.nextInt();
      }
      }while(choice != 2); // the loop will go on till user chooses to exit
   }
      static void deposit() // created a method which takes no values and also returns no values
      {
  
      Scanner keyboard = new Scanner(System.in);
      BankAccount[] account = new BankAccount[2];        // created an array account[] using the BankAccount class provided by book
  
      account[0] = new BankAccount("88","John Smith");   // filled the array as required by the BankAccount class constructor
      account[1] = new BankAccount("99","Robert Jones"); // passing to string values containing account number and account name 
  
      System.out.print("Enter the account number: ");    // ask user to enter the account number        
      String accNum = keyboard.nextLine();               // declare a String variable 'accNum' to take account number from user
  
      String num0 = account[0].getAccountNumber();       // access the account numbers held in the account array 
      String num1 = account[1].getAccountNumber();       // using two string variables num0 and num1 to hold these strings
  
      if(accNum.equals(num0))                        // compare two strings accNum and num0 to confirm account number entered by user is correct
      {
        System.out.print("How much would you like to deposit: ");  // user will deposit here
        double depositAmount = keyboard.nextDouble();              // created a double variable depositAmount to take entered amount
  
        account[0].deposit(depositAmount);                         // using BankAccount class deposit method to enter amount into account
        System.out.println("The current balance is "   account[0].getBalance());  // using BankAccount class getBalance method to get Balance
      }
      else if(accNum.equals(num1))       // same as above for account[0] on line 48 but this time for account[1]
      {
        System.out.print("How much would you like to deposit: ");
        double depositAmount = keyboard.nextDouble();
        account[1].deposit(depositAmount);
        System.out.println("The current balance is "   account[1].getBalance());
      }
      }
   /*
      {    
  
        System.out.println("The Account belonging to "   account[0].getAccountName()   " with Account Number "   account[0].getAccountNumber());
        System.out.println(" has the balance: "   account[0].getBalance());
  
  
        System.out.println("The Account belonging to "   account[1].getAccountName()   " with Account Number "   account[1].getAccountNumber());
        System.out.println(" has the balance: "   account[1].getBalance());
        
      }
  
      */
  
  }
  

The BankAccount Class file is below

   
   
   public class BankAccount
   {
   // the attributes
   private String accountNumber;
   private String accountName;
   private double balance;
   
  // the methods
  
  // the constructor
  public BankAccount(String numberIn, String nameIn)
  {
  accountNumber = numberIn;
  accountName = nameIn;
  balance = 0;
  }
  
  // methods to read the attributes
  public String getAccountName()
  {
  return accountName;
  }
  
  public String getAccountNumber()
  {
  return accountNumber;
  }
  
  public double getBalance()
  {
  return balance;
 }
  
  // methods to deposit and withdraw money
  public void deposit(double amountIn)
  {
  balance = balance   amountIn;
  }
  public boolean withdraw(double amountIn)
  {
      if(amountIn > balance)
      {
        return false; // no withdrawal was made
      }
      else
      {
    balance = balance - amountIn;
    return true; // money was withdrawn successfully
  }
    }
  }
  

I do not know how to send the account[] array to get printed in the main method when the user requests to exit the program as I do not know what type of array it is. I wish to know how to send this array to the main method please.

CodePudding user response:

So what I meant in my comment was something like this.

class ProgEx4 {
  public static void main(String[] args) {
    // create an array with two accounts
    BankAccount[] accounts = new BankAccount[2];
    // fill the array with your account objects
    accounts[0] = new BankAccount("88","John Smith");
    accounts[1] = new BankAccount("99","Robert Jones");

    String accountNumber = readAccountNumber();
    double depositAmount = readAmount();

    BankAccount depositTo = findAccountWithNumber(accountNumber, accounts);
    depositTo.deposit(depositAmount);
  }

  // TODO:

  // returns the account with the given number in the given array
  private static BankAccount findAccountWithNumber(String number, BankAccount[] searchIn) { ...  }
  private static String readAccountNumber() { ... }
  private static double readAmount() { ... }
}

findAccountWithNumberis essentially just iterating the array until you find an account with the given number. You'll also have to include logic what to do if no such account exists, but both is good practice.

CodePudding user response:

you can define the accountArray as a class static variable,rather than a member variable in deposit method. Then you can init this static variable when the class loading.

CodePudding user response:

If you're asking how to display the contents of an array, a simple way to do so is using the default Arrays#toString(arr) method.

int[] arr   = {1, 2, 3, 4, 5};
String str1 = java.util.Arrays.toString(arr);

StringBuilder[] strings = {new StringBuilder("Hello, Java"), new StringBuilder(":)")};
String str2             = java.util.Arrays.toString(strings);

System.out.printf(%s%n%s, str1, str2);

I would also heavily recommend learning how to override your class' toString() method: that way, you can get a more comprehensible String to print.

public class BankAccount {
  .. all of your other methods here.

  @Override
  public String toString() {
    return String.format("%s's Bank Account [#%s] has a balance of %f", this.getAccountName(), this.getAccountNumber(), this.getAccountBalance());
  }
}

In your main method, or wherever you call to print an account object, you can simply write System.out.print(yourAccountObject) by itself without having to deal with String formatting or anything special.

Hope this helped! :)

  • Related