public class Numbers2
{
public static void main(String[] args)
{
int number;
int numberTwo;
int jordan;
number = 5;
numberTwo = 10;
sum(number, numberTwo);
difference (number, numberTwo);
product (number, numberTwo);
System.out.println(jordan);
}
public static void sum(int number, int numberTwo, int jordan)
{
System.out.print("The sum of the numbers is");
System.out.println((number + numberTwo));
}
public static void difference(int number, int numberTwo, int jordan)
{
System.out.print(" The difference of the two numbers is");
System.out.println((number - numberTwo));
}
public static void product(int number, int numberTwo, int jordan)
{
jordan = number * numberTwo;
return jordan;
}
}
错误是:
H:\Numbers2.java:10: sum(int,int,int) in Numbers2 cannot be applied to (int,int)
sum(number, numberTwo);
^
H:\Numbers2.java:11: difference(int,int,int) in Numbers2 cannot be applied to (int,int)
difference (number, numberTwo);
^
H:\Numbers2.java:12: product(int,int,int) in Numbers2 cannot be applied to (int,int)
product (number, numberTwo);
^
H:\Numbers2.java:28: cannot return a value from method whose result type is void
return jordan;
^
4 errors
答案 0 :(得分:0)
更改您的代码...
public class Numbers2
{
public static void main(String[] args)
{
int number;
int numberTwo;
int jordan;
number = 5;
numberTwo = 10;
sum(number, numberTwo);
difference (number, numberTwo);
product (number, numberTwo);
}
public static int sum(int number, int numberTwo)
{
System.out.print("The sum of the numbers is");
System.out.println((number + numberTwo));
return number + numberTwo; // returns addition
}
public static intdifference(int number, int numberTwo)
{
System.out.print(" The difference of the two numbers is");
System.out.println((number - numberTwo));
return number - numberTwo; // returns the subtraction
}
public static int product(int number, int numberTwo)
{
jordan = number * numberTwo;
return jordan; // returns the product
}
}
答案 1 :(得分:0)
您似乎对如何在Java中定义和调用方法感到困惑。
我看到你的方法每个都有三个参数,但第三个参数是在你的方法中设置并返回的。定义方法时,在定义参数之前声明输出的type
。在您的情况下,您当前将其定义为void
。这告诉编译器您的方法不返回任何内容。在您的情况下,您想告诉它您的方法返回一个整数。这方面的一个例子如下:
public static int product(...
此外,当您调用方法时,您的调用必须与方法的签名匹配。这意味着您必须传入相同数量和类型的参数。在您的情况下,您的方法都被声明为输入三个int
s,但是当您调用它们时,您只传入两个。
最后,我看到您传入一个名为jordan
的参数,并尝试修改其值。默认情况下,java通过值"传递对象" (从技术上讲,它传递对象的引用,引用本身是"值")。如果要实际修改参数的值,则必须在包装器对象中传递它。但是,在大多数情况下,您需要在方法内部创建一个新变量并返回该变量。一个例子如下:
// note the "int" keyword before the method name
public static int product(int number, int numberTwo)
{
int jordan = number * numberTwo; // create a new variable to hold our response
return jordan; // returns the product
// You can also just return the result of an operation:
//return number * numberTwo;
}