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 22, 2014
Are you sure the ":" is only for true or false statements? I've seen it used in several different occasions before, but can't remember how exactly they were used.
0 Homer Simpson · November 22, 2014
It might be used for other things but that's the only way I know how to use it. :/ 
0 Developer John · November 23, 2014
For instance, an enhanced for loop.
0 Homer Simpson · November 19, 2014
/images/forum/upload/2014-11-19/550fb71820605444dd2f4f5e776b5021.jpg
0 Developer John · November 19, 2014
Lol thanks Homer!
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 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
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
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
Thanks!

Java / Android Development

107,173 followers
About

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

Links
Moderators
Bucky Roberts Administrator