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.

Code: 

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

-Thanks!8-)

Post a Reply

Replies

- page 2
Oldest  Newest  Rating
0 Developer John · November 19, 2014
Oops, I meant:
average /= Array.length;
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 Homer Simpson · November 19, 2014
No problem. :woot:
0 Developer John · November 19, 2014
Thanks!
0 Homer Simpson · November 19, 2014
Well an array is a reference to the first element in the array. But if you don't tell Java how many elements you're going to store it wouldn't know how much memory to set aside for it. An int is 4 bytes.  

int Array = new int[2];

We're letting Java know, "hey man, I want to make an array with 2 elements in it. so set aside 8 bytes of memory for me." 
0 Developer John · November 19, 2014
I still don't understand. Doesn't the primitive data type already tell Java how much memory the array needs?
0 Homer Simpson · November 19, 2014
When you declare an array you're letting Java know how much memory to set aside for the elements in the array. The array itself starts at 0. 
0 Developer John · November 19, 2014
Wait, actually why did you set the Array element to:
int Array[] = new int[2];


Wouldn't it be 1 since Java counts 0 first?
0 Developer John · November 19, 2014
Lol thanks Homer!
0 Homer Simpson · November 19, 2014
/images/forum/upload/2014-11-19/550fb71820605444dd2f4f5e776b5021.jpg

Java / Android Development

129,827 followers
About

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

Links
Moderators
Bucky Roberts Administrator