6 Questions

+4 Developer John · November 18, 2014
1. What does static mean?
2. What does null mean?
3. What does final mean?
4. Isn't a constructor basically when you want to assign a value to something right before it is used?
5. What is casting and why is it useful?
6. What is wrong with this?

Here, I'm trying to make a program that calculates the average of two variables input by a scanner with text on the screen as well.


import java.util.Scanner;

class Test{

public static void main (String [] args){

Scanner scan = new Scanner(System.in);

System.out.println("Enter two numbers so I can calculate the average.");

int Array[] = new int[2];
int average, sum = 0;

for(int counter = 0; counter < Array.length; counter++){

int Input = scan.nextInt();
Array[1] = Input;
int Input2 = scan.nextInt();
Array[2] = Input2;
sum = sum + Array[counter];
average = sum / Array.length;
System.out.println("The average of the ten numbers is " + average);


I have no errors, yet the program throws we an Exception. I would like to know why exactly I'm getting one. The Exception is the ArrayIndexOutOfBoundsException


Post a Reply


- page 3
Oldest  Newest  Rating
0 Homer Simpson · November 19, 2014
No problem. :woot:
0 Developer John · November 19, 2014
You have your average variable set to 0:
int average = 0;

Whereas you change the value of it:
average += Array[counter];
average /= Array.length();
0 Developer John · November 19, 2014
Oops, I meant:
average /= Array.length;
0 Homer Simpson · November 19, 2014
I like to initialize my variables when I declare them. Just good practice in my opinion. 
average += Array[counter] is the same as
average = average + Array[counter];

So the first time we loop through I'm setting "average" equal to whatever the user enters in.  Say they enter in 100. So now average is equal to 100. Next time around I will be adding what the user enters in to 100. Say they entered in 50. Average would be equal to 150.

average /= Array.length; again thats the same as
average = average / Array.length;

When I declared my array int Array = new int[2];
I told java that my array length is going to be 2.

So average = average / Array.length is the same as
average = 150 / 2

The reason I did it like that is say for example I wanted to get the average of three numbers. I could just change my Array size to 3
int Array = new Array[3] and thats all I would have to do. The code still works.
-1 Developer John · November 20, 2014
Ok, lets just say I have a class and a method:
class Test{
public static void Eat(){

Why wouldn't I have to make an object for the class and then get the method?

Java / Android Development


Very popular language used to create desktop applications, website applets, and Android apps.

Bucky Roberts Administrator