Question

Breaking it Down Problem One problem that I find in new Java programmers is a tendency...

Breaking it Down Problem One problem that I find in new Java programmers is a tendency to put too much code in "main()". It is important to learn how to break a program down into methods and classes. To give you practice at this, I have a program that has too much code in main. Your job will be to restructure the code into appropriate methods to make it more readable. I will provide you with lots of coaching on how to do this. :-) In order to show you what this looks like I have a program below that does too much in main. This program has the following characteristics:

•It repeatedly allows the user to select the mathematical operation desired and operands. Then the mathematical problem is calculated and printed out.•It continues until the user enters a 'q' for quit.•This program is robust in that it doesn't blow up even if the user enters in bad data. I will give you sample output of this program to show you this characteristic.•Except for the fact that is long and all of the code is in main, it is better written and easier to understand than most programs that I see where the programmer has put too much code in main. However, it is harder to understand than it needs to be if we would just break the logic down to smaller methods.•You can copy the code below and run it yourself to try it out. Here is some sample output that I have created:Enter an Operator: + - * / q for quit: +Enter operand 1123Enter operand 245

123 + 45 = 168

=======================

Enter an Operator: + - * / q for quit: -

Enter operand 1

12x

Your last input was bad, try again

56

Enter operand 2

67

56 - 67 = -11

=======================

Enter an Operator: + - * / q for quit: @

Your operator is bad ... try again:

Enter an Operator: + - * / q for quit: *

Enter operand 1

23!

Your last input was bad, try again

23

Enter operand 2

45

23 * 45 = 1035

=======================

Enter an Operator: + - * / q for quit: q

Finished Calculations

TooMuchInMain program:

package breaking_it_down;

import java.util.Scanner;

public class TooMuchInMain {

public static void main(String[] args)

{

Scanner scan = new Scanner(System.in);

int operand1, operand2, answer;

char operator='q';

boolean keepCalculating = true;

while (keepCalculating)

{

//*************************************************

// This next block will get the user desired operator

// getOperator should contain the following logic

//*************************************************

boolean operator_is_good=false;

do

{

System.out.print("Enter an Operator: + -* / q for quit: ");

String strOperator = scan.nextLine();

strOperator = strOperator.trim();

if (strOperator.length() == 0)

continue; // Need to try this again with no input

operator = strOperator.charAt(0);

operator_is_good=false;

switch (operator)

{

case 'q':

case '+':

case '-':

case '*':

case '/':

operator_is_good = true;

break;

default:

System.out.println("Your operator is bad ... try again:");

break;

}

} while (!operator_is_good);

//***********************************************

// At this point operator contains a proper operator chosen by the user

// This will show up in doCalculation

//***********************************************

if (operator == 'q')

{

keepCalculating=false; // not really needed because we are doing a break... but clarifies what will happen

break;

}

//***********************************************

// Now get operand 1

// getOperand() will get the next hunk of logic

//***********************************************

int which =1;

System.out.println("Enter operand "+which);

String input;

boolean operand_is_bad;

do

{

operand_is_bad=false;

input = scan.nextLine();

input = input.trim();

if (input.length() == 0)

operand_is_bad=true;

for (int i=0; i < input.length(); i++)

{

char c = input.charAt(i);

if (c < '0' || c > '9')

{

// Oops, bad digit

operand_is_bad=true;

System.out.println("Your last input was bad, try again");

}

}

} while (operand_is_bad);

// The following statement will be covered later in the course.

// For now, just know that it converts a String to an integer

// Note that Integer.parseInt is picky and blows up with any bad characters

operand1 = Integer.parseInt(input);

//***********************************************

// Now get operand 2

// Note this code is mostly the same as the above code.

// You can just reuse the same getOperand method again

//***********************************************

which =2;

System.out.println("Enter operand "+which);

do

{

operand_is_bad=false;

input = scan.nextLine();

input = input.trim();

if (input.length() == 0)

operand_is_bad=true;

for (int i=0; i < input.length(); i++)

{

char c = input.charAt(i);

if (c < '0' || c > '9')

{

// Oops, bad digit

operand_is_bad=true;

System.out.println("Your last input was bad, try again");

}

}

} while (operand_is_bad);

// The following statement will be covered later in the course.

// For now, just know that it converts a String to an integer

// Note that Integer.parseInt is picky and blows up with any bad characters

operand2 = Integer.parseInt(input);

//***********************************************

// Now we have operator, operand1, and operand2.

// Time to calculate the answer

// doArithmetic will take the following logic

//***********************************************

switch(operator)

{

case '+':

answer = operand1 + operand2;

break;

case '-':

answer = operand1 - operand2;

break;

case '*':

answer = operand1 * operand2;

break;

case '/':

answer = operand1 / operand2;

break;

default:

System.out.println("We shouldn't get here in doArithmentic!!!!");

answer = -1;

break;

}

//***********************************************

// Time to format the answer

// the format routine will get the following statement

//***********************************************

System.out.println(operand1 + " "+ operator + " "+ operand2 + " = "+ answer);

System.out.println("=======================");

} // end of while (continue_calculating)

System.out.println("Finished Calculations");

} // end of main

} // end of class TooMuchInMain BreakingItDown Starting Point for your solution where you have the above logic broken down: Copy into your MP3_worksheet.txt file output from YOUR program that replicates the output above for the TooMuchInMain program. HINT: Note you can copy a lot of code segments from the "TooMuchInMain" into your "BreakingItDown" program. package breaking_it_down; import java.util.Scanner; public class BreakingItDown {

// instance variable

Scanner scan = new Scanner(System.in);

// Top Level routine for doing a single calculation

boolean doCalculation()

{

int operand1, operand2, answer;

char operator = getOperator();

if (operator == 'q')

return false;

operand1 = getOperand(1);

operand2 = getOperand(2);

answer = doArithmetic(operator, operand1, operand2);

format(operator, operand1, operand2, answer);

return true;

}

// Get the Operator reliably

char getOperator()

{

char operator='q';

// ***********************************

// Logic to get a correct operator from the user goes here

// ***********************************

return operator;

}

// Get one operand reliably

int getOperand(int which)

{

System.out.println("Enter operand "+which);

String input;

// ***********************************

// Logic to get a correct operand from the user goes here.

// Hint: collect the users operand into the "input" variable

// Remove excess whitespace (trim call). Make sure all characters are

// digits (i.e. between '0' and '9'). If not, then ask the user for

// another input. Once you have a good "input" string, the statement

// below will convert it to an integer.

// ************************************

// The following statement will be covered later in the course.

// For now, just know that it converts a String to an integer

// Note that Integer.parseInt is picky and blows up with any bad characters

// ***********************************

return Integer.parseInt(input);

}

// Do the Actual Calculation required

int doArithmetic(char operator, int operand1, int operand2)

{

int answer;

// ***********************************

// Your logic to compute the answer

// ***********************************

return answer;

}

// Format the final results

void format(char operator, int operand1, int operand2, int answer)

{

// ***********************************

// Your logic to format the result. For example:

// 23 * 45 = 1035

// ***********************************

}

// We like to keep minimal code in main

public static void main(String[] args)

{

// Construct our class

BreakingItDown bid = new BreakingItDown();

// Call doCalculation for each calculation we are doing.

while (bid.doCalculation())

{

System.out.println("=======================");

} // end of while (continue_calculating)

System.out.println("Finished Calculations");

}

}

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

package test;
import java.util.Scanner;
public class BreakingItDown {

// instance variable

Scanner scan = new Scanner(System.in);

// Top Level routine for doing a single calculation

boolean doCalculation(){
   int operand1, operand2, answer;
   char operator = getOperator();
   if (operator == 'q')
       return false;
   operand1 = getOperand(1);
   operand2 = getOperand(2);
   answer = doArithmetic(operator, operand1, operand2);
   format(operator, operand1, operand2, answer);
   return true;
}

// Get the Operator reliably

char getOperator(){
   char operator='q';
   boolean operator_is_good=false;
   do{
       System.out.print("Enter an Operator: + -* / q for quit: ");
       String strOperator = scan.nextLine();
       strOperator = strOperator.trim();
       if (strOperator.length() == 0)
           continue; // Need to try this again with no input
       operator = strOperator.charAt(0);
       operator_is_good=false;
       switch (operator){
       case 'q':
       case '+':
       case '-':
       case '*':
       case '/':
       operator_is_good = true;
       break;
      
       default:
           System.out.println("Your operator is bad ... try again:");
       break;
       }

} while (!operator_is_good);

//***********************************************

// At this point operator contains a proper operator chosen by the user

// This will show up in doCalculation

//***********************************************

return operator;

}

// Get one operand reliably

int getOperand(int which){
   System.out.println("Enter operand "+which);
   boolean operand_is_bad;
   String input;

// ***********************************

// Logic to get a correct operand from the user goes here.

// Hint: collect the users operand into the "input" variable

// Remove excess whitespace (trim call). Make sure all characters are

// digits (i.e. between '0' and '9'). If not, then ask the user for

// another input. Once you have a good "input" string, the statement

// below will convert it to an integer.

// ************************************

// The following statement will be covered later in the course.

// For now, just know that it converts a String to an integer

// Note that Integer.parseInt is picky and blows up with any bad characters

// ***********************************


   do {
       operand_is_bad=false;
       input = scan.nextLine();

       input = input.trim();
       if (input.length() == 0)
           operand_is_bad=true;
       for (int i=0; i < input.length(); i++){
           char c = input.charAt(i);
           if (c < '0' || c > '9'){
               operand_is_bad=true;
               System.out.println("Your last input was bad, try again");
               }
       }//for

} while (operand_is_bad);

return Integer.parseInt(input);

}

// Do the Actual Calculation required

int doArithmetic(char operator, int operand1, int operand2)

{

int answer;

switch(operator)

{

     case '+':

     answer = operand1 + operand2;

     break;

     case '-':

     answer = operand1 - operand2;

     break;

     case '*':

     answer = operand1 * operand2;

      break;

     case '/':

      answer = operand1 / operand2;

      break;

      default:

      System.out.println("We shouldn't get here in doArithmentic!!!!");

      answer = -1;

      break;

}

return answer;

}

// Format the final results

void format(char operator, int operand1, int operand2, int answer)

{

// ***********************************

// Your logic to format the result. For example:

// 23 * 45 = 1035

// ***********************************
   System.out.println(operand1 + " "+ operator + " "+ operand2 + " = "+ answer);

   System.out.println("=======================");

}

// We like to keep minimal code in main

public static void main(String[] args)

{

// Construct our class

BreakingItDown bid = new BreakingItDown();

// Call doCalculation for each calculation we are doing.

while (bid.doCalculation())

{

System.out.println("=======================");

} // end of while (continue_calculating)

System.out.println("Finished Calculations");

}

}

--------------------------------------------------------------------------------------------------------------------------------------

As asked, parts of programs segment has been put form TooMuchInMain to BreakingItDown. Almost same code has been put and its functioning.

Add a comment
Know the answer?
Add Answer to:
Breaking it Down Problem One problem that I find in new Java programmers is a tendency...
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
  • Hi. This is a prototype of Java. The following Java program was developed for prototyping a...

    Hi. This is a prototype of Java. The following Java program was developed for prototyping a mini calculator. Run the program and provide your feedback as the user/project sponsor. (Save the code as MiniCalculator.java; compile the file: javac MiniCalculator.java; and then run the program: java MiniCalculator). HINTs: May give feedback to the data type and operations handled by the program, the way the program to get numbers and operators, the way the calculation results are output, the termination of the...

  • Java Assignment Calculator with methods. My code appears below what I need to correct. What I...

    Java Assignment Calculator with methods. My code appears below what I need to correct. What I need to correct is if the user attempts to divide a number by 0, the divide() method is supposed to return Double.NaN, but your divide() method doesn't do this. Instead it does this:     public static double divide(double operand1, double operand2) {         return operand1 / operand2;     } The random method is supposed to return a double within a lower limit and...

  • Write a program that takes in a line of text as input, and outputs that line of text in reverse.

    Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Quit", "quit", or "q" for the line of text.Ex: If the input is:Hello there Hey quitthen the output is:ereht olleH yeHThere is a mistake in my code I can not find. my output is : ereht olleH ereht olleHyeHHow can I fix this?I saw some people use void or the function reverse but we didnt...

  • In this lab, you complete a partially written Java program that includes two methods that require...

    In this lab, you complete a partially written Java program that includes two methods that require a single parameter. The program continuously prompts the user for an integer until the user enters 0. The program then passes the value to a method that computes the sum of all the whole numbers from 1 up to and including the entered number. Next, the program passes the value to another method that computes the product of all the whole numbers up to...

  • In this lab, you complete a partially written Java program that includes two methods that require...

    In this lab, you complete a partially written Java program that includes two methods that require a single parameter. The program continuously prompts the user for an integer until the user enters 0. The program then passes the value to a method that computes the sum of all the whole numbers from 1 up to and including the entered number. Next, the program passes the value to another method that computes the product of all the whole numbers up to...

  • ram reads user input with command line argument, two inte ment, two integers and in between...

    ram reads user input with command line argument, two inte ment, two integers and in between tor. The programme will determine whether the input is valid, an rompt info if not. Read the codes, design the isNumber0 method t progran an operator. The program. (5 marks) public class ArithmeticTest ( public static void main(Stringl] args) ( if (isNumber(args[e]) & isNumber(args[2])) ( int value1 Integer.parseInt (args[e]); int value Integer.parseInt (args [2]); char op args[1].charAt (e); calcAndDisplay (value1, value2, op); ) else...

  • JAVA I need a switch so that users can input one selection then another. These selections...

    JAVA I need a switch so that users can input one selection then another. These selections are for a simple calculator that uses random numbers 1. + 2. - 3. * 4./ 5. RNG. This has to be simple this is a beginners class. Here is what I have import java.util.Scanner; import java.util.Random; import java.util.*; public class You_Michael02Basic_Calculator {    public static void main(String[] args) {        // Generate random numbers        int num1,num2;        num1 =(int)(Math.random()*100+1);...

  • Hi I need help with a java program that I need to create a Airline Reservation...

    Hi I need help with a java program that I need to create a Airline Reservation System I already finish it but it doesnt work can someone please help me I would be delighted it doesnt show the available seats when running the program and I need it to run until someone says no for booking a seat and if they want to cancel a seat it should ask the user to cancel a seat or continue booking also it...

  • Let's fix the displayMenu() method! First, edit the method to do the following: We want to...

    Let's fix the displayMenu() method! First, edit the method to do the following: We want to also allow the user to quit. Include a "Quit" option in the print statements! Have it get the user input from within the method itself and return an int based on the user's choice. (Make sure to also edit the method header and how it is called back in the main() method!) What is the method's return type now?                  ...

  • Java. Java is a new programming language I am learning, and so far I am a...

    Java. Java is a new programming language I am learning, and so far I am a bit troubled about it. Hopefully, I can explain it right. For my assignment, we have to create a class called Student with three private attributes of Name (String), Grade (int), and CName(String). In the driver class, I am suppose to have a total of 3 objects of type Student. Also, the user have to input the data. My problem is that I can get...

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
ADVERTISEMENT