|
|
|||||||||
|
|||||||||
|
|||||||||
| |
|||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Beginner and I need a little help
I am trying to make an array that will sum 16 numbers. This is what I got so far:
public class ArrayMatrix { /** Main Method */ public static void main(String[] args) { int [][] Matrix = { {1, 2, 4, 5}, {6, 7, 8, 9}, {10, 11, 12, 13}, {14, 15, 16, 17} }; Matrix = new int[3][3]; int Sum = 0; int number = 0; for (int i = 0; i < 16; i++) { String numberString = JOptionPane.showInputDialog(null, "Enter a integer: ", "Example 5.6 Input", JOptionPane.QUESTION_MESSAGE); Sum = (number + Sum); } String output = "The sum of the numbers you entered is: " + Sum; JOptionPane.showMessageDialog(null, output, "Example 5.6 output", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } I keep getting 0 when I add everything together though. I am using BlueJ and any help will be appreciated. |
|
#2
|
||||
|
||||
|
You write the following code :
Code:
int [][] Matrix = {
{1, 2, 4, 5},
{6, 7, 8, 9},
{10, 11, 12, 13},
{14, 15, 16, 17}
};
Matrix = new int[3][3];
It seems to me that the first declaration is superfluous. You declare Matrix twice, so it's only the last declaration of an empty Matrix you will be using in the rest of your program. Then you initialize sum and number Code:
int Sum = 0; int number = 0; In the loop you note numberString but you don't do anything with it. You add number (which is 0) to Sum (which is also 0). So, at the end, you're bound to keep on getting zeros. Code:
for (int i = 0; i < 16; i++) {
String numberString = JOptionPane.showInputDialog(null,
"Enter a integer: ",
"Example 5.6 Input", JOptionPane.QUESTION_MESSAGE);
Sum = (number + Sum);
}
|
|
#3
|
|||
|
|||
|
try get rid of this line Matrix = new int[3][3];
to see whether it solves your problem |
![]() |
| Viewing: Dev Articles Community Forums > Programming > Java Development > Beginner and I need a little help |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|