Java编写计算器报Incompatible operand types类型不兼容错误求助
Java自定义计算器编译错误排查与修正
错误根因汇总
你遇到的所有编译错误本质都是类型不匹配+基础语法使用错误,逐个对应说明:
Incompatible operand types Scanner and String:你的if判断写错了比较对象。input是Scanner类型的输入工具实例,本身不存储用户输入的运算符内容,你拿Scanner对象直接和字符串"s"/"a"/"m"用==比较,两个完全不同类型的值做相等判断,就会抛出这个错误。你存储用户输入运算符的变量是名为operator的字符串,不是input。Incompatible operand types int and String:这个错误来自两处:- 你最初写switch逻辑时,直接把String类型的
operator作为switch的判断参数,但case标签写的是1、2、3这类int整数值,字符串和整数类型无法匹配判断; - 你后来加的
int op = Integer.valueOf(operator)逻辑本身不成立:用户输入的运算符是a/s/m这类字母,不是数字格式的字符串,Integer.valueOf()只能把纯数字的字符串转成int,传字母进去运行时会直接抛数字格式转换异常。
- 你最初写switch逻辑时,直接把String类型的
- 其他会导致运行异常的语法问题:
- 用
==判断字符串内容相等是错误写法,==判断的是两个对象的内存地址,不是字符串实际内容,比较字符串内容必须用equals()方法 - 调用
nextInt()读取整数后,控制台的换行符不会被读取,直接调用nextLine()会读到空字符串,需要额外消费掉残留的换行 - switch的每个case分支末尾没加
break,会发生case穿透,执行完当前分支后会继续执行后面所有case的代码 - 你定义的名为
String的静态方法和JDK自带的字符串类重名,且方法逻辑完全没有被调用,属于冗余代码 - try-catch块位置错误,把运算逻辑放在catch块外面,根本捕获不到输入非法、数值小于0的异常
- 用
修正后可运行代码
import java.util.Scanner; public class assignmentB { public static void main(String[] args) { Calculator c1 = new Calculator(); Scanner input = new Scanner(System.in); c1.name = "The total is $"; try { int x, y; System.out.println("Red River College"); System.out.println("Custom Calculator"); System.out.println("Enter first value: "); x = input.nextInt(); // 校验输入值合法性 if (x < 1) { throw new Exception("Value must be larger than 0."); } System.out.println("Enter second value: "); y = input.nextInt(); if (y < 1) { throw new Exception("Value must be larger than 0"); } // 消费nextInt残留的换行符 input.nextLine(); System.out.println("Enter operation(a=Add, s=Subtract, m=multiply): "); String operator = input.nextLine(); // 直接用字符串做switch判断(Java 7及以上版本原生支持) switch (operator) { case "s": System.out.println(c1.name + c1.subtract(x,y)); break; case "a": System.out.println(c1.name + c1.add(x,y)); break; case "m": System.out.println(c1.name + c1.multiply(x,y)); break; default: System.out.println("Invalid operation input, please enter a/s/m"); } } catch (Exception e1) { System.out.println(e1.getMessage()); } finally { input.close(); } } }
注:代码默认你项目中的Calculator类已经实现了
add/subtract/multiply三个运算方法,且包含name属性,可以直接调用。
内容的提问来源于stack exchange,提问作者Jeseca Z
相关产品推荐
相关产品推荐

