I have created a class. Inside the class, I have created a method called "createVessel()" which should return a string array. I want to call that method from the same class and store the returned string array in another string array variable (not even sure if I can do that).
Anyway, when I call the method, the IDE causes an error and thinks that I am trying to create another method by the same name and suggesting me to change the name. Can someone please let me know what I am doing wrong? In other words, why aren't I able to call the createVessel() method? (Note: I will post all the code within the createVessel() method just to add context even though it may not be necessary to answer my question).
package submarineGame;
import java.util.*;
public class GameControl {
//Create Vessel Method
String[] carry = new String[2];
carry = createVessel();
String[] createVessel(){
// code here that creates an String array of positions
return positions;
}
Direct solution:
String[] carry = createVessel();
Why? The problem is that you can't execute assignments to fields directly in the body of a class - if it's not in the direct declaration of fields. For this purpose you have the constructor where you could write something like:
public GameControl(){
carry = createVessel();
}
Then you could stay with String[] carry = new String[2];
because the String[]
which will be created inside the createVessel()
method would override it. Another way would to use a main method:
public static void main(String[] args) {
carry = createVessel();
}
But of course you then need to also assign static
to the String[] carry
and the method createVessel();
If you have another question, feel free to comment - I will be back on this question later. Also I can see you are not really familiar with Java so maybe the Oracle Tutorials will help http://docs.oracle.com/javase/tutorial/ a little bit.