过去两天我一直在努力解决这个问题。我不知道我的代码中的哪一点我犯了错误。请帮忙!
import java.util.Scanner;
class Program3
{
private static Scanner inp;
public static void main(String args[])
{
double number1;
double number2;
inp = new Scanner(System.in);
double repeat = 0;
do
{
System.out.println("Please enter a number.");
number1 = inp.nextDouble();
System.out.println("Please enter a second number.");
number2 = inp.nextDouble();
System.out.println(" You have chosen numbers, " +number1+ ", and " +number2++);
double add;
double subtract;
double multiply;
double divide;
double choice;
add = number1+number2;
subtract = number1-number2;
multiply = number1*number2;
divide = number1/number2;
System.out.println("What type of operation would you like to run? ");
System.out.println("Please enter the number that corresponds with the operation.");
System.out.println("Please note, that if your dividing number is equal to 0, the operation will return and error message.");
System.out.println("1. add");
System.out.println("2. subtract");
System.out.println("3. multiply");
System.out.println("4. divide");
choice = inp.nextInt();
if (choice == 1)
{choice = add;
System.out.println("By adding " +number1+ " to " +number2+ " the answer is " +choice++);
}
else if (choice == 2)
{choice = subtract;
System.out.println("By subtracting " +number1+ " and " +number2+ " the answer is " +choice++);
}
else if (choice == 3)
{choice = multiply;
System.out.println("By multiplying " +number1+ " by " +number2+ " the answer is " +choice++);
}
else if (choice == 4)
{choice = divide;
System.out.println("By dividing " +number1+ " from " +number2+ " the answer is " +choice++);
}
if (number2 == 0)
System.out.println("Error: Number cannot be divisible by 0. Please choose another number");
System.out.println("Would you like to try other numbers?");
System.out.println("Enter 1 to continue");
repeat = inp.nextDouble();
} while (repeat == 1);
inp.close();
}
}
结果如下
Please enter a number.
2
Please enter a second number.
3
You have chosen numbers, 2.0, and 3.0
What type of operation would you like to run?
Please enter the number that corresponds with the operation.
Please note, that if your dividing number is equal to 0, the operation will return and error message.
1. add
2. subtract
3. multiply
4. divide
1
By adding 2.0 to 4.0 the answer is 6.0
Would you like to try other numbers?
Enter 1 to continue
如你所见。用户输入的数字和操作中的数字相差1,我在代码中找不到错误。谢谢你的帮助!
答案 0 :(得分:3)
在以下一行
System.out.println(" You have chosen numbers, " +number1+ ", and " +number2++);
通过执行此操作,您将number2
递增一个
number2++
这称为增量,它的作用是通过加1来增加数值变量的值。
最后删除那些++
,它应该有效。
答案 1 :(得分:0)
当你做"选择++"时,这意味着增加"选择"的值。一个人。
答案 2 :(得分:0)
答案已在此处公布。
但不是在选择时使用if-else条件,而是必须根据用户的选择使用switch语句并制作案例。