java: adding array elements
Dear all,
I wish to write a Java application program and an applet program that find the sum of all the integers in the array shown below and print them out together with the sum as below:
int[ ][ ]MyArray={{2, 3, 4, 5 }, {6, 7,8}, {9, 10}, {11}}
expected output:
2 3 4 5
6 7 8
9 10
11
Total = 28 20 12 5
(eg col1 6+2+9+11=28, col2: 3+7+10=20, col3: 8+4=12, col4: 5)
That is, the program arranges all first elements in one column, all second elements in another vertical column, etc and displays as output as shown above.. Then it sums them up the corresponding elements and displays them as Total = 24 17 10 4 as above. When I try, am getting wrong values for the sum and am unable to display the elements in vertical column.
Here is my code for the application program part:
public class AssignmtOneQuiz1 {
public static void main(String args[]) {
int sum = 0;
int[ ][ ]MyArray={{2, 3, 4, 5 }, {6, 7,8}, {9, 10}, {11}};
System.out.print("Total = ");
for(int i=0; i<MyArray.length; i++)
{
for(int j=0; j<MyArray[i].length; j++)
sum += MyArray[i][j];
System.out.print(sum + " ");
}
}
Butt it's not giving the required results. lease assist.
Thanks
}
Re: java: adding array elements
Everytime you're outputting the "sum", which accumulates all your terms, so this is why you get higher and higher values everytime. At some point, you need to stop accumulating the past values, and start with the new ones.
Got it? :)
application context
Re: java: adding array elements
Hi Daniel. Got it.
Infact the code now works perfect.
However, it only works as an application. How can I write the same code such that it is done in an applet this time and not application since application is ok?
please help
Re: java: adding array elements
You need to read about how to write an applet. Go to this site and Find applet:
The Really Big Index
When you have code that executes as an applet, you can add your logic to it. One change you'll need to make is that the output should go to a field in the GUI and not be via println.
The GUI code will be the same as for an application, so I'd suggest that you change your program to output the results to a GUI field and then use that same code in the applet.