Search code examples
javacalculator

How can I make a calculator ask the user if they want to perform another calculation in Java?


I have tried to do this using a do while loop however the variable isn't found. My goal is to basically perform the code all over again when the user wants to. Can anybody help?

import java.util.Scanner;
public class Calculator {
    public static void main(String args[]) {
        do{
            Scanner typed=new Scanner(System.in);
            System.out.println("Please type: 1 for add, 2 for subtract, 3 for multiply or 4 for divide");
            int userInput=typed.nextInt();
            System.out.println("Please enter the first number to calculate:");
            double number1=typed.nextDouble();
            System.out.println("Please enter the second number to calculate:");
            double number2=typed.nextDouble();
            if (userInput==1){
                System.out.println("The answer is");
                double result=number1+number2;
                System.out.println(result);
            }
            if (userInput==2){
                System.out.println("The answer is");
                double result=number1-number2;
                System.out.println(result);
            }
            if (userInput==3){
                System.out.println("The answer is");
                double result=number1*number2;
                System.out.println(result);
            }
            if (userInput==4){
                System.out.println("The answer is");
                double result=number1/number2;
                System.out.println(result);
            }
                System.out.println("Do you want to perform another calculation? Press 1 for yes or 2 for no.");
                int pressed=typed.nextInt();
            
        }while(pressed==1);
            
    }
}

Solution

  • You're trying to use a variable outside of its scope.

        do{
          // ...
          int pressed=typed.nextInt();
            
        }while(pressed==1);  // Outside of the scope of 'pressed'
    

    You can address this by moving the declaration outside the loop, but leaving the assignment.

        int pressed = 1;
    
        do{
          // ...
          pressed=typed.nextInt();
            
        }while(pressed==1);  // Outside of the scope of 'pressed'