Java双文件实现计算器时如何将week1.java输入变量传递到Switch.java
问题原因
你在week1类的main方法里定义的num1、num2、operator1都是方法局部变量,作用域仅限main方法内部,Switch类没有权限直接访问这些变量,且你调用switchcase()方法时未将变量作为参数传递,所以Switch类无法识别这些变量。
修复方案
第一步 修改Switch.java的方法定义
给switchcase()方法添加入参,接收运算需要的两个数字和运算符:
public class Switch { // 新增3个入参:第一个操作数、运算符、第二个操作数 void switchcase(int num1, char operator1, int num2) { int operator2 = 0; // 运算结果变量移到方法内部定义 switch(operator1){ case '+': operator2 = num1 + num2; System.out.println("Addition: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 ); break; case '-': operator2 = num1 - num2; System.out.println("Subtraction: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 ); break; case '*': operator2 = num1 * num2; System.out.println("Multiplication: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 ); break; case '/': // 补充除数为0判断,避免运行崩溃 if(num2 == 0){ System.out.println("错误:除数不能为0"); return; } operator2 = num1 / num2; System.out.println("Division: " + num1 + " " + operator1 + " " + num2 + " = " + operator2 ); break; // 补充非法运算符处理 default: System.out.println("错误:不支持的运算符"); } } }
第二步 修改week1.java的方法调用
调用switchcase()时将三个变量作为参数传入:
import java.util.Scanner; public class week1 { public static void main(String[] args) { int num1; int num2; Scanner input = new Scanner(System.in); System.out.print("Input a number:"); num1 = input.nextInt(); System.out.print("Input a Math :"); char operator1 = input.next().charAt(0); System.out.print("Input a number:"); num2 = input.nextInt(); Switch swish = new Switch(); // 传递三个参数到switchcase方法 swish.switchcase(num1, operator1, num2); // 关闭输入流避免资源泄漏 input.close(); } }
内容的提问来源于stack exchange,提问作者Pxyke
相关产品推荐
相关产品推荐

