creating an arrary in a class and return the value
I created a class and try to return the array from the class how do I do that? the following code is what I wrote, but it doesnt work. please help Thanks.
public class MyClass
{
public int myField[];
public MyClass(){}
public void SetField(int value)
{myField[0] = value + 10;
myField[1] = value + 20;
myField[2] = value + 30;
}
public int GetField()
{return myField[];}
//-
MyClass aaa = new MyClass();
aaa.SetField(1);
int a[] = aaa.GetField();
[545 byte] By [
aboostera] at [2007-11-26 20:02:47]

public class MyClass
{
public int myField[];
public MyClass(){}
public void SetField(int value)
{ myField[0] = value + 10;
myField[1] = value + 20;
myField[2] = value + 30;
}
public int GetField()//error. Should be public int[] GetField()
{ return myField[]; } //error: should be return myField;
You are telling your method to return 1 single int. When it NEEDS to be returning an array of ints. :)
Message was edited by:
lethalwire
> I created a class and try to return the array from the class how do I do that?
Like this:public class MyClass {
public int[] myField;
public void setField(int value) {
myField = new int[3];
myField[0] = value + 10;
myField[1] = value + 20;
myField[2] = value + 30;
}
public int[] getField() {
return myField;
}
public static void main(String[] args) {
MyClass aaa = new MyClass();
aaa.setField(1);
int[] arr = aaa.getField();
for(int i :arr) {
System.out.println(i);
}
}
}
But I really think you need to work through the general language section of Sun's tutorial (http://java.sun.com/docs/books/tutorial/) or something similar.
> pbrockway2 de-capitalized your SetField method to setField.
Sorry, yes. There were lots of little things I changed and I didn't want to litter the code with comments for things that the OP can figure out for him or herself...
Code conventions are a Good Thing - initial capital for classes, lower case for variables and methods.
There is less confusion if you put the [] next to the rest of the description of the type, even though the language often lets you put them after the variable (or method!). I even did this for the main() method although out of habit I usually write String args[].
@OP Welcome to the forum! You might have noticed that code gets formatted, but might not have realised how this is done. Put [code] at the start of your code and [/code] at the end. That way spaces and things get formatted correctly.
^^ Very right pbrockway.
I was just telling him to make sure he found the error.
I am very big on proper syntax and think you are 100% correct.
The better the syntax, the easier to read.
You would have absolutely hated my latest UIL test. The formatting was absolutely horrid!