Results 1 to 5 of 5
Thread: returning an array weird problem
- 01-28-2011, 04:50 AM #1
Member
- Join Date
- Jan 2011
- Posts
- 3
- Rep Power
- 0
returning an array weird problem
Here's an example of the code i'm having a problem with
Okay better Description. I have an array of temperatures in degrees C and need to convert them into degrees K. I pass the array into the converT function and change each value inside an temp array. I have checked the temp array before returning it and the result is correct. I then return the array and assign it to the new array tempK in the main line. The values that are in tempK do not agree with the values that were in the temp array before i returned it.Java Code:public static double[] convertT(double[] t){ double[] tArray=t; int index=0; for (double num:t){ tArray[index]=num+273.1; index++; } return tArray; } public static void main(String[] args) { double[] tempC = {77.0, 77.0, 63.5, 53.3, 53.3, 77.6, 77.6, 77.6, 52.9, 52.9, 77.6, 62.7, 53.7, 53.7, 79.5, 79.5, 64.0, 64.0, 54.5, 39.2, 38.3, 49.4, 40.2, 40.2, 40.2, 40.2, 39.7, 40.2, 40.2, 40.2, 39.9, 39.9, 39.8}; double[] tempK=convertT(tempC); for (double num:tempK){ System.out.print(num+":"); } }
Any ideas?Last edited by mcleanj; 01-28-2011 at 05:26 AM. Reason: formatting plus description
-
Please edit your post to add code tags so your code is readable. My first link below will tell you how. Also, please provide more detail about your problem. Your current description is a bit unclear to me.
- 01-28-2011, 05:22 AM #3
When you pass Object (and arrays are Objects) you pass a reference to the Object/array and not a copy of it. So in your code the variables tempC, t, tArray and tempK all reference the same array. So when you make a change to one of the variables, all the other variables see that change.
Solution: create a new array in your method.
- 01-28-2011, 05:28 AM #4
Member
- Join Date
- Jan 2011
- Posts
- 3
- Rep Power
- 0
hopefully thats a bit better thanks for the links new to this forum
- 01-28-2011, 05:29 AM #5
Member
- Join Date
- Jan 2011
- Posts
- 3
- Rep Power
- 0
Similar Threads
-
returning double array
By Billaguana in forum New To JavaReplies: 2Last Post: 01-16-2011, 03:59 AM -
Problem returning Array values Please help
By drgnfire25 in forum New To JavaReplies: 4Last Post: 01-12-2011, 12:53 AM -
returning array
By aizen92 in forum New To JavaReplies: 4Last Post: 01-08-2011, 03:10 PM -
Returning An Array
By elektronika in forum New To JavaReplies: 2Last Post: 12-07-2009, 03:43 PM -
Returning array problem.
By Chase in forum New To JavaReplies: 4Last Post: 10-21-2008, 09:07 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks