Results 1 to 3 of 3
- 11-26-2007, 07:53 PM #1
Member
- Join Date
- Nov 2007
- Posts
- 2
- Rep Power
- 0
Adding numbers in a 2 dimensional array
Hey guys I'm new to java and I am looking for some help. I want to create a program that will add up the numbers in a two dimensional array. I have most of the code down but I keep getting errors.
Here's my code:
class averageNum {
// initialize # of rows
int[][] arr = { { 1, 0, 12, -1 },
{ 7, -3, 2, 5 },
{ -5, -2, 2, 9 }
};
int x;
int sum;
public int sum(int num)
{
int total = 0;
}
public int test(int sum){
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; i++)
sum = sum + arr[i][j];
}
public static void main (String[] args){
System.out.println(sum);
}
I get an error in my main method saying "non static variable sum cannot be referenced from a static context"
Any help would greatly be appreciated!
- 11-26-2007, 09:19 PM #2
You need to instantiate an instance of your averageNum class. (BTW it is a good idea to being all of your class names with a capitol letter.) Before you do that, your averageNum needs some touching up.
Java Code:public class AverageNum{ //initialize # of rows int[][] arr = { { 1, 0, 12, -1 }, { 7, -3, 2, 5 }, { -5, -2, 2, 9 } }; public AverageNum(){ //always need a constructor. } int x; //not sure why you need this int sum; //you may not need this either. you can just return the sum from the method //this method doesn't do anything public int sum(int num){ int total = 0; return total; } public int test(){ int sum = 0; for(int i = 0; i < arr.length; i++){ for(int j = 0; j < arr[i].length; j++){ sum = sum + arr[i][j]; } } return sum; } public static void main(String[] args){ AverageNum foo = new AverageNum(); System.out.println(foo.test()); } }
- 11-27-2007, 04:31 AM #3
Member
- Join Date
- Nov 2007
- Posts
- 2
- Rep Power
- 0
Similar Threads
-
How to initialize a two dimensional Array
By Java Tip in forum java.langReplies: 0Last Post: 04-14-2008, 08:48 PM -
Adding numbers in array
By Shaolin in forum New To JavaReplies: 1Last Post: 11-15-2007, 06:30 PM -
generating random numbers in a 5x5 array.
By acidacid in forum New To JavaReplies: 3Last Post: 08-14-2007, 03:44 AM -
Adding graphics to array
By romina in forum Java 2DReplies: 1Last Post: 08-01-2007, 01:45 AM -
Help with array multi-dimensional
By barney in forum New To JavaReplies: 1Last Post: 07-31-2007, 08:00 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks