# Simple Calculator

• March 21st, 2011, 06:13 PM
JKDSurfer
Simple Calculator
Hi everyone!

I'm programming a simple calculator and this is my first time programming. I'm having a bit of difficulty on figuring out this assignment. Everything is working correctly except I need to have the console ask the user if he would like to rerun the program. When the user inputs, "yes" it should start again from the beginning. This is the code I have so far. Do I need to nest all of this code into another loop statement?

Code Java:

```import java.util.*; import javax.swing.*;   public class SimpleCalculator { public static void main (String [] args){ double result = 0.0, temp = result, oldResult = result;   Scanner input = new Scanner(System.in);   //Initialization of Calculator System.out.println("Calculator is on"); System.out.println("result = " + result);   //Calculations String operation = ""; while (!operation.equals("R") && !operation.equals("r")) { operation = input.nextLine();   //Read operator char sign = operation.charAt(0);   //Addition, Subtraction, Multiplication, Division switch (sign){ case '+': temp = Double.parseDouble(operation.substring(1)); oldResult = result; result = result + temp; System.out.println(oldResult + " + " + temp + " = " + result); break; case '-': temp = Double.parseDouble(operation.substring(1)); oldResult = result; result = result - temp; System.out.println(oldResult + " - " + temp + " = " + result); break; case '*': temp = Double.parseDouble(operation.substring(1)); oldResult = result; result = result * temp; System.out.println(oldResult + " * " + temp + " = " + result); break; case '/': temp = Double.parseDouble(operation.substring(1)); oldResult = result; result = result / temp; System.out.println(oldResult + " / " + temp + " = " + result); break; case 'r': break; case 'R': break; default: System.out.println(sign + " is an unknown operation"); System.out.println("Reenter your last line: ");   }   //END }     //Printing of Result System.out.println("Final result = " + result);   //Again Method System.out.println("Again?"); String again = input.nextLine();     }     }```
• March 21st, 2011, 08:26 PM
vanDarg
Re: Simple Calculator
This would best be handled with a do while loop.
Yes, you would have to enclose the code you want within the loop. while and do-while statements
• May 14th, 2011, 10:29 AM
bglueck
Re: Simple Calculator
you could also use a SENTINEL constant value that the user can type to escape the loop. make another switch statement after the
Code :

```System.out.println("Again?"); String again = input.nextLine();```
that would continue for yes(say !(operation.equals(r)) again, which will reiterate the loop) for no, say operation.equals(r) is true, and the SENTINEL value could be 0 or q or something, which would also exit the loop.
• June 28th, 2011, 01:37 PM
weakprogrammer
Re: Simple Calculator
add a Do-While Statement into your code and then run your code. It will work as you want it to.