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



我有两个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);
        }

您不能将 +用于非主要类型(或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);
}

您可以尝试以下方法:

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);
    }
}

相关内容

最新更新