Peter_Browning Peter_Browning - 6 months ago 10
Java Question

How do i properly code this java calculator?

I am creating a java calculator, and I am encountering a situation involving my java scanner being unable to accept any more input.

Here is the code im working with:

import java.util.Scanner;

class RealCalc {

public static void main(String args[]) {
Scanner bucky = new Scanner(System.in);
Scanner reason = new Scanner(System.in);
Scanner finalProduct = new Scanner(System.in);
double fnum, snum, answer;
String YesNo;
String Multiply;
String Add;
String Divide;
String Subtract;
String operation;

// Time to declare the string's value
Multiply = ("Multiply");
Divide = ("Divide");
Subtract = ("Subtract");
Add = ("Add");

System.out.println("Hello, my name is Cortana,"
+ " would you like to perform operations with me?");

YesNo = reason.nextLine();
if (YesNo.equals("Yes")) {
System.out.println("Good choice!");
System.out.println(" ");

System.out.println("Enter your first number");
fnum = bucky.nextDouble();
System.out.println("Enter your second number");
snum = bucky.nextDouble();

System.out.println("What do you want me to do with these numbers?");
operation = finalProduct.nextLine();
if (operation.equals(Multiply)) {

System.out.println(fnum * snum);

} else {

System.out.println("I do not recognize this operation");
}
}
}
}


So basically the problem is near the end when I am trying to find a way to code a thing where it asks you to type an operation you want to perform.

If you say Multiply, Divide, Add, or Subtract, it will do that respected operation with firstNum and secondNum (fnum, snum), but if it is neither of those 4 operations, it will say "I do not recognize this operation.

Now this isn't difficult. The problem is getting to retry typing in an operation.

When it says "I do not recognize" the program im using (eclipse) does not allow me to input any more data.

Please help.

Answer

Here is another simple way to do it: wrapp the code area with the issue in a while(true)and use a break to finish when it has been answered

 while (true) {
     System.out.println("What do you want me to do with these numbers?");
        operation = finalProduct.nextLine();

        if (operation.equals(Multiply)){

            System.out.println(fnum * snum);
            break;

        }else{

            System.out.println("I do not recognize this operation");

        }
     }

This way your application will keep looping every time the user inputs an incorrect operation and will finish only when he inputs Multiply

The construct like while(true) is used to create an infinite loop, so all the code inside the while block will keep running unless it encounters a break, which will happen only when he inputs the right operator and after the program outputs the answers. Otherwise if he inputs something incorrect the program will answer I do not recognize this operationand will start over again by asking him again to input the operator