cannot get this method to work properly
I'm trying to take a given array and increment the capacity by a certain integer. The program runs and returns the original and incremented array with the same length. Any ideas?
Code :
public static void main(String[] args)
{
double[] james=new double[15];
System.out.println("The array james has: "+james.length+" spaces");
expand(james,5);
System.out.println("The array now has: "+james.length+" spaces");
}
public static void expand(double [] x, int howManyMore)
{
double [] newX=new double[x.length+howManyMore];
for(int i=0;i<x.length;i++)
{
newX[i]=x[i];
}
x=new double[newX.length];
for(int i=0;i<newX.length;i++)
{
x[i]=newX[i];
}
}
}
Re: cannot get this method to work properly
It seems you are passing a value to a method and expecting it to be recreated, which is incorrect (google 'java pass by value' for much more information). Rather, return the newly created array and let the caller deal with it. The following code snipped demonstrates, and shows that recreating a parameter object within a method does nothing to the original object.
Code java:
public static void main(String[] args){
String myValue = "myValue";
String returned = changer(myValue);
System.out.println("Original value: " + myValue);
SYstem.out.println("Returned value: " + returned);
}
public static String changer(String value){
value = "new value";
return value;
}
Re: cannot get this method to work properly
Alright, I got it to work. Thanks. I was initially confused because it was supposed to be a void method, and I was having difficulty changing the initial array into the larger one without returning anything. I appreciate your help.