The program starts execution in the main
method. The first statement that Java executes is
setNumbers(x,y);
at that point you didn't define any x
or y
variable. Thus the error.
Note that method(x, y)
means that you want to call a method and give it additional information, two variables, on the way. So you need to provide such variables like
double x = 1;
double y = 2;
setNumbers(x, y);
then the method will be called with those parameters. However, your setNumbers
method doesn't seem to use the variables in any way, you just try to overwrite them:
x = inputs [0] = set.nextDouble();
y = inputs [1] = set.nextDouble();
Which would have no effect on the program since x
and y
inside the method are not connected anymore to the scope outside of the world, Java is pass by value.
If you want the method to assign two variables and then use them later you should call it without arguments and then return the values:
// In main method
double[] numbers = setNumbers();
double x = numbers[0];
double y = numbers[1];
// setNumbers method
public static double[] setNumbers() {
double[] input = new double[2];
input[0] = ...
input[1] = ...
return input;
}
Next, your addNumbers
and multipleNumbers
method have a return type, why? You don't use it, then you don't need it. If you want to use it you should not throw the result away like
double resultAdd = addNumbers(x, y);
double resultMult = multiplyNumbers(x, y);
System.out.println("Result of x + y = " + resultAdd);
System.out.println("Result of x * y = " + resultMult);
Can someone explain why my software intelliJ also says to use static
in all the name of the methods?
Your program execution starts in the main
method, a static
method. At that point no objects are created. static
means something is not bound to a specific object instance. If you want to be able to call non-static methods you would first need to create object instances. Imagine a class like
public class Human() {
public void drink() { ... }
public void eat() { ... }
}
If you want to be able to call drink
or eat
you first need to create some Human
instance like
Human john = new Human();
Human abigail = new Human();
john.eat();
abigail.drink();
The methods are specific to the instance. So john
may still be thirsty since we called drink
only on abigail
. A static
method is not specific to an instance. If we add the following method
public class Human {
public static void getIQ() { ... }
}
It may only be able to return the average IQ of a human, not the IQ of john
. The method does not know anything about instances like john
and we could call it even if we didn't yet create instances like john
. That is also why we should indicate calling of a static
method like
Human.getIQ();
and not as
john.getIQ();
Unfortunately, the second variant is possible and does compile. But it confuses since the call is not executed on john
.
In your code example, since you didn't created any instances of classes, you need static
methods to call them.