0

我正在尝试做一个计算器。这些运算符:x, +, -,/工作正常。

但我希望用户在得到数学问题的答案后能够做两件事。

询问用户是否要继续。

  1. 如果用户输入,yes他可以输入 2 个数字,它会再次计数。
  2. 如果用户类型no只是关闭。

这是我的代码:

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;
        }
    }
}
4

2 回答 2

1

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.

于 2013-09-10T11:52:45.130 回答
0

你可以重构你的代码如下。这可能会帮助你

    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;
        }
    }
于 2013-09-10T11:40:24.837 回答