在标记所有重复之前,请查看代码,因为它以与其他问题不同的方式完成,我将不胜感激与此代码相关的修复。它几乎是一个计算器,需要两个数字,然后一个运算符打印最终数字(如果适用,还有余数)。我得到错误:
The local variable num3 may not have been initialized
The local variable rem may not have been initialized
这是代码:
import java.util.Scanner;
public class JCalc {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int num1;
int num2;
int num3;
int rem;
System.out.println("Welcome to JCalc! The best calculator ever!");
System.out.print("Please enter the first number: ");
num1 = myScanner.nextInt();
System.out.print("Please enter the second number: ");
num2 = myScanner.nextInt();
System.out.print("Please enter an operator (+, -, %, *): ");
String op = myScanner.next();
if (op == "+") {
num3 = num1 + num2;
}
if (op == "-") {
num3 = num1 - num2;
}
if (op == "%") {
num3 = num1 - num2;
rem = num1 % num2;
}
if (op == "*") {
num3 = num1 * num2;
}
System.out.print("The answer is: ");
System.out.print(num3); //error
if (op == "%") {
System.out.print(" with a remainder of ");
System.out.println(rem); //error
}
}
}
最后两个括号在我复制粘贴时有点乱(抱歉)。感谢我能得到的所有帮助!