![](/img/trans.png)
[英]How can I ask a user if they want to modify information and then apply the change?
[英]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.