我是意大利人(印刷的文字是意大利语)。在做了加法之后,程序问我一个输入,然后从这个输入(以及它问的另一个输入)中做一个减法。我不知道这是不是臭虫。有人能帮帮我吗?
import java.util.Scanner;
public class calcolatrice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numero1;
int numero2;
int numero3;
System.out.println("Menu: "
+ "addition (1), "
+ "subtraction (2), "
+ "multiplication (3), "
+ "division (4), "
+ "exponential (5), "
+ "square root (6)");
System.out.println("nEnter the number corresponding to the option you want: ");
int opzione = input.nextInt();
if (opzione == 1) {
System.out.print("Enter the first number: ");
numero1 = input.nextInt();
System.out.print("Enter the second number: ");
numero2 = input.nextInt();
numero3 = numero1 + numero2;
System.out.print("The sum between " + numero1 + " and " + numero2 + " is: " + numero3);
} else if (opzione == 2)
System.out.print("nEnter the first number: ");
numero1 = input.nextInt();
System.out.print("Enter the second number: ");
numero2 = input.nextInt();
numero3 = numero1 - numero2;
System.out.print("The difference between " + numero1 + " and " + numero2 + " is: " + numero3);
}
}
在您的原始代码中,您有这样的逻辑:
if (opzione == 1) {
// do things
} else if (opzione == 2)
// do other things
这段代码有一个微妙的错误:在if
语句的第二个分支中,没有大括号;即不存在{...}
。
这是整个块,我在其中应用了代码格式(独立)和行号:
1 if (opzione == 1) {
2 System.out.print("Enter the first number: ");
3 numero1 = input.nextInt();
4
5 System.out.print("Enter the second number: ");
6 numero2 = input.nextInt();
7
8 numero3 = numero1 + numero2;
9 System.out.print("The sum between " + numero1 + " and " + numero2 + " is: " + numero3);
10
11 } else if (opzione == 2)
12 System.out.print("nEnter the first number: ");
13
14 numero1 = input.nextInt();
15
16 System.out.print("Enter the second number: ");
17 numero2 = input.nextInt();
18
19 numero3 = numero1 - numero2;
20 System.out.print("The difference between " + numero1 + " and " + numero2 + " is: " + numero3);
注释:
- 第12行:缩进一次,对应
if
语句——也就是说,如果opzione
的值为2,它将继续运行第12行。 - 第14行:没有缩进。请注意,代码格式化程序是自动完成的(我使用的是IntelliJ,尽管还有许多其他选项)。格式化程序理解第14行是而不是第11行
if
语句的部分。 - 第16-20行:就像第14行一样,这些是独立于第1行或第11行
if
语句运行的代码行。这就是为什么你观察到,在选择了"添加"选项后,它会提示你添加更多的东西。路径。
修复你的代码:
第11行:在行尾添加一个左括号(
{
),更改如下:} else if (opzione == 2)
:
} else if (opzione == 2) {
第21行:在结尾处添加新行(在调用
的另一端System.out.print
之后),使用单个右括号(}
) -这是{
从第11行