Fix the code in Oops2java so that it is better structured an

Fix the code in Oops2.java so that it is better structured and avoids redundancy. There are some lines of code that are repeated. Think about where you can move the repeated lines in the code so that they only appear once. You do not need to add any error checking on the user input, assume that the user will always enter 1 or 2. Here is the code:

import java.util.Scanner;

public class Oops2 {
public static void main(String[] args) {

      int sum = 0;
      int count = 0;
      int total = 0;

      Scanner console = new Scanner(System.in);

      System.out.print(\"Is your money multiplied 1 or 2 times?\");
      int times = console.nextInt();
      if (times == 1){
          System.out.print(\"And how much are you contributing? \");
          int donation = console.nextInt();
          sum = sum + donation;
          count++;
          total = total + sum;
      }
      if (times == 2){
          System.out.println(\"And how much are you contributing? \");
          int donation = console.nextInt();
          sum = sum + 2 * donation;
          count++;
          total = total + sum;
      }
      System.out.println(\"The total is \" + total);
}
}

Solution

Here is the code without redundant code:

import java.util.Scanner;
public class Oops2 {
public static void main(String[] args) {
int sum = 0;
int count = 0;
int total = 0;
Scanner console = new Scanner(System.in);
System.out.print(\"Is your money multiplied 1 or 2 times?\");
int times = console.nextInt();
if (times == 1 || times==2){
System.out.print(\"And how much are you contributing? \");
int donation = console.nextInt();
sum = sum + times*donation;
count++;
total = total + sum;
}
  
System.out.println(\"The total is \" + total);
}
}

Fix the code in Oops2.java so that it is better structured and avoids redundancy. There are some lines of code that are repeated. Think about where you can move

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site