Java:请求继续

时间:2013-09-10 11:27:58

标签: java eclipse calculator restart

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

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

询问用户是否要继续。

  1. 如果用户输入yes,他会输入2个数字再次计算。
  2. 如果用户输入no,则只需关闭。
  3. 这是我的代码:

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

2 个答案:

答案 0 :(得分:1)

将您的代码放在

do {
    ...
} while (condition);

循环,在你的情况下,如果用户说“是”,则条件类似于wantToContinue

然后程序将不会结束,除非用户不再想要计算。

答案 1 :(得分: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;
        }
    }
相关问题