简体   繁体   中英

Java: Ask for continue

I'm trying to make a calculator. These operators: x , + , - , / work fine.

But I want the user to be able to do 2 things after he gets the answer on his math problem.

Ask user if he wants to continue.

  1. If user types in yes he gets to put in 2 numbers that it counts again.
  2. If the user types no just shut down.

Here's my code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner Minscanner = new Scanner(System.in);
        int nr1 = Integer.parseInt(Minscanner.nextLine());
        int nr2 = Integer.parseInt(Minscanner.nextLine());
        int yes = Integer.parseInt(Minscanner.nextLine());//trying to fix reset
        int ans =0;
        int reset = J;/trying to make it reset if user types in yes
        String anvin = Minscanner.nextLine();

        if(anvin.equalsIgnoreCase("+")) {
            ans = nr1 + nr2;
        }
        else if(anvin.equalsIgnoreCase("-")) {
            ans = nr1 - nr2;
        }
        else if(anvin.equalsIgnoreCase("*")) {
            ans = nr1 * nr2;
        }
        else if(anvin.equalsIgnoreCase("/")) {
            ans = nr1 / nr2;
            System.out.println(ans);
        }
        if(anvin.equalsIgnoreCase("yes")) {
            return;
        }
    }
}

Put your code in a

do {
    ...
} while (condition);

loop, and in your case the condition would be something like wantToContinue if user say "yes".

Then the program will not end unless user no longer wants to calculate.

You can refactor your code as bellow. This may help you

    boolean status=true;
    while (status){
    Scanner scanner = new Scanner(System.in);
    Scanner scanner1 = new Scanner(System.in);
    System.out.println("Enter your two numbers one by one :\n");
    int num1 = scanner.nextInt();
    int num2 = scanner.nextInt();
    System.out.println("Enter your operation you want to perform ? ");
    int ans =0;
    String option = scanner1.nextLine();
    if(option.equalsIgnoreCase("+")) {
        ans = num1 + num2;
    }
    else if(option.equalsIgnoreCase("-")) {
        ans = num1 - num2;
    }
    else if(option.equalsIgnoreCase("*")) {
        ans = num1 * num2;
    }
    else if(option.equalsIgnoreCase("/")) {
        ans = num1 / num2;
    }
    System.out.println(ans);
     System.out.println("you want to try again press y press j for shutdown\n");
   Scanner sc = new Scanner(System.in);
        String input=sc.nextLine();
        if (input.equalsIgnoreCase("J")) {
            System.exit(0);
        } else if (input.equalsIgnoreCase("Y")) {
            status = true;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM