My name’s Ali, I have just started two units of study with the Open University, so I am entirely fresh-faced to Java. I am trying to get the following code to compile but the lack of support i’m getting from my tutor is horrendous and the several books I have splayed out across my room aren’t helping me get going.
I have been given a method that I wish to answer some questions about:
public char[] methodA()
{
char[] alphas = {'s', 't', 'e', 'a', 'm'};
char temp = alphas[0];
int i = 0;
while (i < alphas.length - 1)//1
{
alphas[i] = alphas[i+1]; //2
i++;
}
alphas[alphas.length-1]=temp;
return alphas;
}
How do I get this to compile successfully using my IDE? I have tried just enclosing it within the syntax for my ‘main’ method but it’s not accepting it.
Here is what I have at the moment:
package openuniversity;
public class Main
{
public static void main(String[] args)
{
public static char[] methodA()
{
char[] alphas = {'s', 't', 'e', 'a', 'm'};
char temp = alphas[0];
int i = 0;
while (i < alphas.length - 1)//1
{
alphas[i] = alphas[i+1]; //2
i++;
}
alphas[alphas.length-1]=temp;
return alphas;
}
}
}
Thanks to anyone who can help.
Ali
All methods must be enclosed within a class. If your IDE has already generated that for you, then you should be able to make it a sibling of your main method, as follows:
If you wish to call
methodAfrom your main method, you will either need to:Foo(by sayingFoo x = new Foo())then invoke the method on the object you create (by saying
x.methodA())methodAto be static, by changing its signature topublic, then invoke the method statically (by sayingstatic char[] methodA()
Foo.methodA())