所以这是我的简单计算器代码。它在大多数情况下都有效,我试图在操作结束时创建一个循环,以允许用户选择执行另一个操作或退出。到目前为止,我已经尝试添加嵌套的if循环,但我一直收到错误。任何帮助都会有所帮助。我很新。
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
// Introduction to Calculator providing instructions to user
Scanner input = new Scanner(System.in);
int num1, num2, ans, Y, N;
System.out.println("Welcome to Simple Calculator: Please enter \n" +
"which mathimatical operation you would like to \n "
+ "accomplish by imputing 1-addition, 2-subtraction \n"
+ "3-multiplication, 4-division, 5-modulo");
int Operation = input.nextInt();
//Operation sequence for user to input which operation they would like to accomplish
if (Operation == 1) {
System.out.println("You have Choosen Addition");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 + num2;
System.out.print("Answer is: " + ans);
/*
* Right here in the following I want to put something in to make this loop
* so the user can make multiple calculation.
* So far nothing has worked.
*/
System.out.println("Would you like to do another calculation?\n " +
"Enter Y for Yes or N to Exit");
}else if (Operation == 2){
System.out.println("You have Choosen Subtraction");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 - num2;
System.out.print("Answer is: " + ans);
}else if (Operation == 3){
System.out.println("You have Choosen Multiplication");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 * num2;
System.out.print("Answer is: " + ans);
}else if (Operation == 4){
System.out.println("You have Choosen Division");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 / num2;
System.out.print("Answer is: " + ans);
}else if (Operation == 5){
System.out.println("You have Choosen Modulo");
System.out.print("Enter your First number: ");
num1 = (int) input.nextDouble();
System.out.print("Enter your second number: ");
num2 = (int) input.nextDouble();
ans = num1 % num2;
System.out.print("Answer is: " + ans);
}else{
System.out.print("Invalid Operation, please try again.");
}
}
}
答案 0 :(得分:1)
你在这里走在正确的轨道上。我建议使用do-while循环。所以将整个部分从if (Operation == 1) {
一直包含到最终的else
语句中,如下所示:
do {
/*
if (Operation == 1) {
...
...
...
else {
...
}
*/
System.out.print("Would you like to do another calculation? [Y/n] ");
} while (input.nextLine().toUpperCase().charAt(0) == 'Y');
答案 1 :(得分:0)
我会将整个事情放在while循环中,最后询问是否要继续 是的 - 它会循环回来 不 - 你有它突破循环