有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

错误:(18,29)java:';'预期+错误:(18,39)java:不是语句

它应该问1号、2号和操作员的问题是什么

package com.company;

import java.util.Scanner;


public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter number 1: ");
        int operand1 = scan.nextInt();
        System.out.print("Enter operator: ");
        String operator = new Scanner(System.in).nextLine();

        System.out.print("Enter number 2: ");
        int operand2 =  scan.nextInt();
        if (operator == "+") {
            return int.class(operand1 + operand2);
        }
        else if (operator == "-") {
            return int.class(operand1 - operand2);
        }
        else if (operator == "*") {
            return int.class(operand1 * operand2);
        }
        else {
            return "error...";
        }
    }

}
// Error:(18, 29) java: ';' expected
// Error:(18, 39) java: not a statement

错误 错误:(18,29)java:';'预期+错误:(18,39)java:不是语句


共 (1) 个答案

  1. # 1 楼答案

    有几个问题:

    1. main被声明为void,所以你不应该return任何东西
    2. 字符串比较是用Java中的equals进行的,而不是==
    3. 您可能希望显示结果,而不是返回结果:使用System.out.print而不是return
    4. 如上所述:我不确定你想通过用int.class(...)包装算术运算来做什么,但它没有做你认为它在做的事情

    请参阅下面的更正(或直接运行here):

    import java.util.Scanner;   
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            System.out.print("Enter number 1: ");
            int operand1 = scan.nextInt();
            System.out.print("Enter operator: ");
            String operator = new Scanner(System.in).nextLine();
    
            System.out.print("Enter number 2: ");
            int operand2 =  scan.nextInt();
            if (operator.equals("+")) {
                System.out.print(operand1 + operand2);
            } else if (operator.equals("-")) {
                System.out.print(operand1 - operand2);
            } else if (operator.equals("*")) {
                System.out.print(operand1 * operand2);
            } else {
                System.out.print("error: unknown Operation: " + operator);
            }
        }
    
    }