Java:要求继续
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18717746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Ask for continue
提问by user2764700
I'm trying to make a calculator. These operators: x
, +
, -
, /
work fine.
我正在尝试制作一个计算器。这些运算符:x
, +
, -
,/
工作正常。
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.
询问用户是否要继续。
- If user types in
yes
he gets to put in 2 numbers that it counts again. - If the user types
no
just shut down.
- 如果用户输入,
yes
他可以输入 2 个数字,再次计数。 - 如果用户键入
no
只是关闭。
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;
}
}
}
回答by Ruchira Gayan Ranaweera
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;
}
}
回答by Eel Lee
Put your code in a
把你的代码放在一个
do {
...
} while (condition);
loop, and in your case the condition would be something like wantToContinue
if user say "yes".
循环,在您的情况下,条件类似于wantToContinue
用户说“是”。
Then the program will not end unless user no longer wants to calculate.
然后程序不会结束,除非用户不再想计算。