Go4Expert (http://www.go4expert.com/)
-   Programming (http://www.go4expert.com/forums/programming-forum/)
-   -   Problem with array manipulation (http://www.go4expert.com/forums/array-manipulation-t16768/)

 channel 2Apr2009 11:38

Problem with array manipulation

I'm trying to solve a cubic equation. A cubic equation has three solutions for x and I want the values of x to be stored in an array int_array. The problem that I'm having is that I'm getting double results for each x. I want to access the first value of x by writing the following: int_array[0], the second value by int_array[1] and the third value by int_array[2]. The other problem is that if I try to access int_array[1], I get [3,0,0], the same result that I get when I try to access int_array[0] and int_array[2].

Here is the code that I wrote to solve the problem:

Code:

public class Equation {

public void doCalculations(int a, int b, int c, int d){
int j;
for (int i=-10;i<=10;i++){
if((a*(i*i*i)+ b*(i*i)+ c*(i)+ d)==0){
j=i;
int int_array[] = new int[3];
for(int k=0;k<int_array.length;k++)
int_array[k]=j;

System.out.println("The value of X1 is :" + int_array[0]);
System.out.println("The value of X2 is :"+ int_array[1]);
System.out.println("The value of X3 is :"+ int_array[2]);

}
}
}

public static void main(String[]args){
Equation equation = new Equation();
equation.doCalculations(1, -6, 11, -6);
}

}

Here are sample results that I get after running the program:

The value of X2 is :1
The value of X3 is :1
The value of X1 is :2
The value of X2 is :2
The value of X3 is :2
The value of X1 is :3
The value of X2 is :3
The value of X3 is :3

May anyone out there help me, I'm stuck and I dont know where to begin now. I also accept direct postings to channel.zhou@yahoo.com. Thank you in advance.

 xpi0t0s 2Apr2009 13:05

Re: Problem with array manipulation

Please use code blocks when posting code.

What do you think the output should be and why (i.e. what do you think you are displaying)?

What are you trying to do with this code? :
Code:

for(int k=0;k<int_array.length;k++)
int_array[k]=j;

 xpi0t0s 2Apr2009 13:11

Re: Problem with array manipulation

You seem to be recreating the int array every time the result of the equation is zero, then assigning the same value to each of the three locations. So probably what you want to do is to create the array outside the loop and set j=0, then inside the loop, when the result is zero, assign i to int_array[j++], and maybe use a safety cutout in case j exceeds 2 because due to integer arithmetic that could well happen (why aren't you using double variables?)

 All times are GMT +5.5. The time now is 19:12.