129k views
3 votes
The following code is poorly structured. Rewrite it so that it has a better structure and avoids redundancy. To help eliminate redundancy, convert the code into a method named spending that accepts two parameters: a Scanner for the console, and a String for a single person's name, and prints the appropriate information about that person's bills. Your method could be called twice (once for John and once for Jane) to replicate the original code's behavior.

Scanner console = new Scanner(System.in);
System.out.print("How much will John be spending? ");
double amount = console.nextDouble();
System.out.println();
int numBills1 = (int) (amount / 20.0);
if (numBills1 * 20.0 < amount) {
numBills1++;
}
System.out.print("How much will Jane be spending? ");
amount = console.nextDouble();
System.out.println();
int numBills2 = (int) (amount / 20.0);
if (numBills2 * 20.0 < amount) {
numBills2++;
}
System.out.println("John needs " + numBills1 + " bills");
System.out.println("Jane needs " + numBills2 + " bills");

User Efritz
by
5.1k points

1 Answer

3 votes

Answer:

Step-by-step explanation:

public static void main(String[] args) {

Scanner console = new Scanner(System.in);

spending(console,"John"); //calling spending method with "John"

spending(console,"Jane"); //calling spending method with "Jane"

}

public static void spending(Scanner console, String name){

System.out.print("How much will "+name+" be spending? ");

double amount = console.nextDouble();

System.out.println();

int numBill = (int) (amount / 20.0);

if (numBill * 20.0 < amount) {

numBill++;

}

System.out.println("John needs " + numBill + " bills");

}

Code Explanation

Method are reusable set of code which reduces redundancy. So the original code was trying to calculate the bill for John and Jane but the code to calculate was redundant which will cause more line of code and complex to manage. For example let say if we have 1000 of user to calculate there bill, will it be efficient to write bill calculation code for all 1000 users?

That's where function comes in to reduce redundancy from code and easy to manage.

Easy to Manage in a way, let say you need to change the bill calculation formula then without function, you have to change the formula for all the users but with function you only need to change the bill calculation formula in spending function.

User Desco
by
6.6k points