首页 文章

我有2个java错误,我需要帮助!错误:无法比较的类型:二进制运算符的扫描程序和字符串以及错误的操作数类型'+'

提问于
浏览
-1

我有两个java错误,我需要帮助解决,请帮助!!

错误1:无法比较的类型:扫描程序和字符串

错误2:二元运算符的错误操作数类型''

这是我的代码:

import java.util.Scanner;
public class calculator {
    public static void main(String[] args) {
        Scanner x = new Scanner(System.in);
        x.nextInt();
        Scanner y = new Scanner(System.in);
        y.nextInt();
        Scanner function = new Scanner(System.in);
        function.next();
        if (function == "add") {
            int sum = x + y;
            System.out.println(sum);
        }

2 回答

  • 0

    您不能将 + 用于非基本类型(或 String ) . 在您的情况下,您尝试将其用于 Scanner 参考 .

    你可能意味着:

    Scanner scanner = new Scanner(System.in);
    int x = scanner.nextInt();
    int y = scanner.nextInt();
    String function = scanner.next();
    if (function == "age") {
        int sum = x + y;
        System.out.println(sum);
    }
    
  • 0

    你可以试试这个:

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
    
        System.out.println("List of functions: 'age'");
        System.out.println("Please enter the function:");
        String function = reader.next();
    
        System.out.println("Enter the first age:");
        int x = reader.nextInt();
        System.out.println("Enter the second age:");
        int y = reader.nextInt();
    
        if (function.equalsIgnoreCase("age")) {
            int sum = x + y;
            System.out.println("Total is: " + sum);
        }
    }
    

相关问题