繁体   English   中英

如何让计算器询问用户是否想在 Java 中执行另一个计算?

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

我尝试使用 do while 循环来执行此操作,但是找不到该变量。 我的目标是基本上在用户想要的时候重新执行代码。 有人可以帮忙吗?

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

您正在尝试使用其范围之外的变量。

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

您可以通过将声明移到循环外但保留分配来解决此问题。

    int pressed = 1;

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

pressed在循环主体之后留下范围 将 press 的声明pressed do之前。

int pressed = 0;
do {
    // ...
    pressed=typed.nextInt();
} while(pressed==1);

或者,您可以将循环更改为无限循环while(true); 并使用

int pressed = typed.nextInt();
if (pressed != 1) {
    break; // End the infinite loop
}

只需在 do while 循环之外声明“按下”变量。

int pressed;
do 
{
 //code
}

并从int pressed=typed.nextInt(); 这一行使其变为pressed=typed.nextInt();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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