0

I have created two classes. In the first class, I have tried to make a method in another class to return a value with a command to output value on the console. But I get an error that says there are incompatible types. Here are two classes that I have created and I wanted to make a calculator out of that: The first class

class calc1
{
    public static int num1; //first number variable
    public static int num2; //Second number variable
    public static String op; //Operatior variable
    public static void main(String[] args) //
    {
        num1 = Integer.parseInt(args[0]);
        num2 = Integer.parseInt(args[2]);
        op = args[1];
        calc3.calculate(op); //Calling method from the second class with an arugement.
    }
}

this is the second:

class calc3
{
    public static int calculate(String ops)
    {
        switch(ops) //I believe that ops stores value from op variable in the first class.
        {
        case "+": 
            {
                int num = calc1.num1 + calc1.num2;
                return (System.out.println(num));
            }

        }
    }
}

Here is an error message I get from a compiler:

Desktop$ javac calc1.java
./calc3.java:10: error: incompatible types
        return (System.out.println(num));
                                  ^
 required: int
 found:    void
1 error

PS. I was wondering if that the process I am doing is called overloading methods?

4

4 回答 4

2

System.out.println返回void。您的“计算”方法返回int.

如果您想打印数字并在您的方法中返回它,您应该将代码更改为:

System.out.println(num);
return num;

PS:您似乎没有在其中重载任何方法。

于 2013-06-15T06:59:54.620 回答
0

在你的下课中

class calc3
{
public static int calculate(String ops)
{
switch(ops) //I believe that ops stores value from op variable in the first class.
{
case "+": 
    {
        int num = calc1.num1 + calc1.num2;
        return (System.out.println(num));
    }

}
}
}

你回来System.out.println(num)了,而你应该只是回来num

calc3.calculate()期望一个 int 作为返回类型。

随着您的进步并开始进行大量编码,您可能希望使用 Eclipse 或 NetBeans 等 IDE 来帮助您更好地调试编译错误和运行时错误。

于 2013-06-15T07:07:38.583 回答
0

你需要了解一些java的基本概念,比如

System.out.println(num);语句只打印并且不返回任何内容。

因此,当它的返回类型为 int 时,您的计算方法不会返回任何内容,而是返回 void。

您需要返回一个 int 值,该值也应该在条件语句之外(当然您也可以在条件语句中返回),但为了满足编译器的要求,应该至少有一个外部条件语句,例如 viz。

只有这样是行不通的

System.out.println(num);

return num;

return num;确保您在侧开关块之外也有一个类似返回的语句 ( )。

于 2013-06-15T07:17:19.553 回答
0

以下是一些评论:

  • 在这种情况下,编译器消息非常清楚。正如 Mena 所指出的,System.Out.Println()是一个不返回任何内容的函数( void)。但是,您的calculate函数应该返回一个int.

  • 正如其他人所指出的,您需要返回一个值

    int num = calc1.num1 + calc1.num2;
    return (System.out.println(num));
    

可能变成:

    return calc1.num1 + calc1.num2;
  • 是的,我确实省略了System.out.println声明。我认为您可以为此目的使用调试器。

  • 没有案例的switch陈述default是不好的。在这种情况下,直接从 switch 返回一个值是可以接受的,但是构造 switch 语句的“正常”方式使用break. 请参阅oracle 教程

  • Calc1类名通常以大写字母 ( , Calc2...)开头。这只是一个约定。

  • 您的代码中没有重载。您可能想顺便看看覆盖:重载与覆盖

于 2013-09-22T18:39:27.747 回答