Question

Can you help me rearrange my code by incorporating switch I'm not really sure how to...

Can you help me rearrange my code by incorporating switch I'm not really sure how to do it and it makes the code look cleaner. Can you help me do it but still give the same output? Also kindly add an in-line comment on what changes and rearrangement you've done so I can understand what's going on.

import java.util.ArrayList;

import java.util.Scanner;

public class Bank {

/**
* Add and read bank information to the user.
* @param arg A string, double and int array containing
* the command line arguments.
* @exception Any exception
* @return an arraylsit of bank customers
*/

// method to display the menu
static void menu() {

System.out.println("\n1. Add a bank customer");

System.out.println("2. Remove a bank customer");

System.out.println("3. Print all bank customers");

System.out.println("4. Quit");

}

// method to add a customer in sorted order of account number into an array

// list. returns true if addition is successful, else false

static boolean addCustomer(ArrayList<BankCustomer> customers,

BankCustomer newCustomer) {

// looping and finding the proper position to add

for (int i = 0; i < customers.size(); i++) {
  
// checking if new customer can be added to index i
  
if (newCustomer.getAcctNumber() < customers.get(i).getAcctNumber()) {

// adding to index i

customers.add(i, newCustomer);

return true; // success

} else if (newCustomer.getAcctNumber() == customers.get(i)

.getAcctNumber()) {

// duplicate found, returning false

return false;

}
  
}

// adding to the end, if still not added

customers.add(newCustomer);

return true; // success

}

// method to remove a customer by account number, if exists

static boolean removeCustomer(ArrayList<BankCustomer> customers,

int accountNum) {

for (int i = 0; i < customers.size(); i++) {
  
if (customers.get(i).getAcctNumber() == accountNum) {

// found, removing current customer

customers.remove(i);

return true; // found and removed

}
  
}

return false; // not found

}

// method to print customers

static void printCustomers(ArrayList<BankCustomer> customers) {

// displaying heading

System.out.printf("%-15s %-15s %-15s\n", "Customer Name",

"Account Number", "Account Balance");

// looping and printing each customer's name, acc num and balance

for (BankCustomer c : customers) {
  
System.out.printf("%-15s %-15d $%-14.2f\n", c.getName(),
  
c.getAcctNumber(), c.getBalance());
  
}

System.out.println("-----------------------------------------------\n");

}

// main method

public static void main(String[] args) {

// creating an array list of BankCustomer

ArrayList<BankCustomer> accounts = new ArrayList<BankCustomer>();

// scanner to read user input

Scanner scanner = new Scanner(System.in);

int ch = 0;

// looping until ch is 4

do {
  
// displaying menu
  
menu();
  
// inside try with multiple catches block, getting and processing
  
// user input
  
try {

System.out.print("Enter your choice: ");

//reading choice

ch = Integer.parseInt(scanner.nextLine());

System.out.println();

if (ch == 1) {
  
//reading details for bank customer
  
System.out.print("Enter name: ");
  
String name = scanner.nextLine();
  
System.out.print("Enter account number: ");
  
int accNum = Integer.parseInt(scanner.nextLine());
  
System.out.print("Enter balance: ");
  
double balance = Double.parseDouble(scanner.nextLine());
  
  
  
//creating a customer, will throw BCException if any detail is invalid
  
BankCustomer cust = new BankCustomer(accNum, balance, name);
  
//if no exception occurred, adding to the list and displaying the result
  
if (addCustomer(accounts, cust)) {

System.out.println("Success!");

} else {

System.out

.println("Customer with same account number already exists!");

}
  
} else if (ch == 2) {
  
//fetching an account number, removing customer
  
System.out.print("Enter account number: ");
  
int accNum = Integer.parseInt(scanner.nextLine());
  
if (removeCustomer(accounts, accNum)) {

System.out.println("Success!");

} else {

System.out

.println("Customer with given account number does not exist!");

}
  
} else if (ch == 3) {
  
//printing customers
  
printCustomers(accounts);
  
}

} catch (BCException e) {

//BCException is occurred

System.out.println(e.getMessage());

} catch (Exception e) {

//exception due to non numeric input

System.out.println("Invalid input!");

}
  
} while (ch != 4);

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1


ANSWER:-

CODE AFTER REARRANGEMENT:-

import java.util.ArrayList;
import java.util.Scanner;

public class Bank {
   /**
   * Add and read bank information to the user.
   * @param arg A string, double and int array containing
   * the command line arguments.
   * @exception Any exception
   * @return an arraylsit of bank customers
   */

   // method to display the menu
   static void menu() {
       System.out.println("\n1. Add a bank customer");
       System.out.println("2. Remove a bank customer");
       System.out.println("3. Print all bank customers");
       System.out.println("4. Quit");
   }

   // method to add a customer in sorted order of account number into an array
   // list. returns true if addition is successful, else false
   static boolean addCustomer(ArrayList<BankCustomer> customers,BankCustomer newCustomer) {
       // looping and finding the proper position to add
       for (int i = 0; i < customers.size(); i++) {
           // checking if new customer can be added to index i
           if (newCustomer.getAcctNumber() < customers.get(i).getAcctNumber()) {
               // adding to index i
               customers.add(i, newCustomer);
               return true; // success
           } else if (newCustomer.getAcctNumber() == customers.get(i).getAcctNumber()) {
               // duplicate found, returning false
               return false;
           }
       }
       // adding to the end, if still not added
       customers.add(newCustomer);
       return true; // success
   }
   // method to remove a customer by account number, if exists
   static boolean removeCustomer(ArrayList<BankCustomer> customers,int accountNum) {

       for (int i = 0; i < customers.size(); i++) {
           if (customers.get(i).getAcctNumber() == accountNum) {
               // found, removing current customer
               customers.remove(i);
               return true; // found and removed
           }
       }
       return false; // not found
   }
   // method to print customers
   static void printCustomers(ArrayList<BankCustomer> customers) {
       // displaying heading
       System.out.printf("%-15s %-15s %-15s\n", "Customer Name","Account Number", "Account Balance");
       // looping and printing each customer's name, acc num and balance
       for (BankCustomer c : customers) {
           System.out.printf("%-15s %-15d $%-14.2f\n", c.getName(),          
           c.getAcctNumber(), c.getBalance());      
       }
       System.out.println("-----------------------------------------------\n");
   }
   // main method
   public static void main(String[] args) {
       // creating an array list of BankCustomer
       ArrayList<BankCustomer> accounts = new ArrayList<BankCustomer>();
       // scanner to read user input
       Scanner scanner = new Scanner(System.in);
       int ch = 0;
       // looping until ch is 4
       do {
           // displaying menu
           menu();
           // inside try with multiple catches block, getting and processing
           // user input
           try {
               System.out.print("Enter your choice: ");
               //reading choice
               ch = Integer.parseInt(scanner.nextLine());
               System.out.println();
               int accNum;
               // use switch instead if-else if,
               // using switch case for menu is better.
               switch(ch) {
                   case 1:
                       //reading details for bank customer
                       System.out.print("Enter name: ");
                       String name = scanner.nextLine();
                       System.out.print("Enter account number: ");
                       accNum = Integer.parseInt(scanner.nextLine());
                       System.out.print("Enter balance: ");
                       double balance = Double.parseDouble(scanner.nextLine());
                       //creating a customer, will throw BCException if any detail is invalid
                       BankCustomer cust = new BankCustomer(accNum, balance, name);
                       //if no exception occurred, adding to the list and displaying the result
                       if (addCustomer(accounts, cust)) {
                           System.out.println("Success!");
                       } else {
                           System.out.println("Customer with same account number already exists!");
                       }  
                       break;      
                   case 2:              
                       //fetching an account number, removing customer              
                       System.out.print("Enter account number: ");
                       accNum = Integer.parseInt(scanner.nextLine());                  
                       if (removeCustomer(accounts, accNum)) {
                           System.out.println("Success!");
                       } else {
                           System.out.println("Customer with given account number does not exist!");
                       }
                       break;              
                   case 3:              
                       //printing customers              
                       printCustomers(accounts);
                       break;              
               }
           } catch (BCException e) {
               //BCException is occurred
               System.out.println(e.getMessage());
           } catch (Exception e) {
               //exception due to non numeric input
               System.out.println("Invalid input!");
           }
       } while (ch != 4);
   }
}

NOTE:- I have not changed anything in the code's logic. I replaced if-else if with switch case. And gave indentation properly. So, you will get output as before. If you have any doubts, please comment below.

   THUMBS UP!!!! THANK YOU!!!!

Add a comment
Know the answer?
Add Answer to:
Can you help me rearrange my code by incorporating switch I'm not really sure how to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Can you help me rearrange my code to make it look cleaner but still give the...

    Can you help me rearrange my code to make it look cleaner but still give the same output? Also kindly add an in-line comment on what changes and rearrangement you've done so I can understand what's going on. import java.util.ArrayList; import java.util.Scanner; public class Bank { /** * Add and read bank information to the user. * @param arg A string, double and int array containing * the command line arguments. * @exception Any exception * @return an arraylsit of...

  • (How do I remove the STATIC ArrayList from the public class Accounts, and move it to...

    (How do I remove the STATIC ArrayList from the public class Accounts, and move it to the MAIN?) import java.util.ArrayList; import java.util.Scanner; public class Accounts { static ArrayList<String> accounts = new ArrayList<>(); static Scanner scanner = new Scanner(System.in);    public static void main(String[] args) { Scanner scanner = new Scanner(System.in);    int option = 0; do { System.out.println("0->quit\n1->add\n2->overwirte\n3->remove\n4->display"); System.out.println("Enter your option"); option = scanner.nextInt(); if (option == 0) { break; } else if (option == 1) { add(); } else...

  • Hi All, Can someone please help me correct the selection sort method in my program. the...

    Hi All, Can someone please help me correct the selection sort method in my program. the output for the first and last sorted integers are wrong compared with the bubble and merge sort. and for the radix i have no idea. See program below import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class Sort { static ArrayList<Integer> Data1 = new ArrayList<Integer>(); static ArrayList<Integer> Data2 = new ArrayList<Integer>(); static ArrayList<Integer> Data3 = new ArrayList<Integer>(); static ArrayList<Integer> Data4 = new ArrayList<Integer>(); static int...

  • Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args)...

    Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); final int maxSize = 128; String[] titles = new String[maxSize]; int[] lengths = new int[maxSize]; int numDVDs = 0; String op; op = menu(stdIn); System.out.println(); while (!op.equalsIgnoreCase("q")) { if (op.equalsIgnoreCase("a")) { if (numDVDs < maxSize) numDVDs = addDVD(titles, lengths, numDVDs, stdIn); } else if (op.equalsIgnoreCase("t")) searchByTitle(titles, lengths, numDVDs, stdIn);    else if (op.equalsIgnoreCase("l")) searchByLength(titles, lengths, numDVDs, stdIn); System.out.println('\n');...

  • Below, you can find the description of your labwork for today. You can also find the...

    Below, you can find the description of your labwork for today. You can also find the expected output of this code in the Application Walkthrough section. You are going to improve your existing Money & Stock Trading Platform on previous week’s labwork by incorporating Collections. In previous labworks, you have used arrays for holding Customer and Item objects. For this labwork you need to use ArrayList for holding these objects. So, rather than defining Customer[] array, you need to define...

  • Hello, can someone please fix my code? It runs perfect but I'm having trouble with the...

    Hello, can someone please fix my code? It runs perfect but I'm having trouble with the index for the incorrect answer array; please run some tests to ensure the code runs properly, thank you! Here is the code: ___________________________________________________________________________________________________________________________ import java.util.Scanner; public class DriverTest{    final static int QuestionTotal = 10;    public static void main(String[] args){          // scanner and answer key        Scanner scan = new Scanner(System.in);        final char[] answers = {'A', 'B', 'C',...

  • composed the following java code to read a string from a text file but receiving compiling...

    composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file. Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated. import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Main {   public static void main(String[] args) {     System.out.print("Enter the...

  • Could you help me pleas , this is my code I want change it to insert...

    Could you help me pleas , this is my code I want change it to insert student by user , and i have problem when i want append name it just one time i can't append or present more one. >>>>>>>>>>>>>>>>>>>. import java.util.Iterator; import java.util.Scanner; public class studentDLLTest { static int getChoice() { Scanner in = new Scanner(System.in); int choice; do { System.out.print("\nYour choice? : "); choice = in.nextInt(); } while (choice < 1 || choice > 9); return choice;...

  • My Question is: I have to modify this program, even a small modification is fine. Can...

    My Question is: I have to modify this program, even a small modification is fine. Can anyone give any suggestion and solution? Thanks in Advanced. import java.util.*; class arrayQueue { protected int Queue[]; protected int front, rear, size, len; public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } public boolean isEmpty() { return front == -1; } public boolean isFull() { return front == 0 && rear ==size...

  • Need help debugging. Create an application that keeps track of the items that a wizard can...

    Need help debugging. Create an application that keeps track of the items that a wizard can carry. console application which has no errors: import java.util.Scanner; public class Console {        private static Scanner sc = new Scanner(System.in);     public static String getString(String prompt) {         System.out.print(prompt);         String s = sc.nextLine();         return s;     }     public static int getInt(String prompt) {         int i = 0;         boolean isValid = false;         while (!isValid) {             System.out.print(prompt);...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT