I am trying to use a for loop to create 7 instances of a class. I can go through the loop 7 times, but once I press enter I get an ArrayIndexOutOfBound error.
My code is as follows:
Data[] temperatures = new Data[7];
for(int i=1; i<=temperatures.length + 1; i++)
{
System.out.println("Please enter the temperature for day " + i);
temperatures[i] = new Data(input.nextDouble());
}
Array indexes start at 0. Therefore you must loop this way
for(int i=0; i < temperatures.length; i++)
That is because array index starts with 0, and it must not be greater than the array size.
In your case it starts from 1 to 8 and you array size is 7.
for(int i=0; i<temperatures.length; i++)
{
System.out.println("Please enter the temperature for day " + (i+1));
temperatures[i] = new Data(input.nextDouble());
}
ArrayIndexOutOfBoundsException
public class ArrayIndexOutOfBoundsException
extends IndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
This line is causing the error.
for(int i=1; i<=temperatures.length + 1; i++)
Your i in the loop should start from 0 as arrays in Java start from the 0th index.. Also your loop should go till i
This will navigate smoothly for 7 times.
Try this
for(int i=0; i < temperatures.length; i++)
Array indexes start at 0. The problem with your code is that you are trying to access the 8th array element which doesn't exist. For more information, refer The Java™ Tutorials - Arrays.
Your code should look something like this:
Data[] temperatures = new Data[7]; // Indexes 0-6 (makes a total of 7 indexes)
// Start the loop from index 0, end it to index 6 (= temperatures.lenght)
for (int i = 0; i < temperatures.length; i++) {
// Since it would sound strange to enter a temperature for day 0, notice (i+1)
System.out.println("Please enter the temperature for day " + (i+1));
temperatures[i] = new Data(input.nextDouble());
}
Arrays have index starting from 0 . IN your case indices would be 0 to 6
Solution :
1. Change Loop to for(int i=0; i
Related
In my program, I want to display an array using Scanner, i.e the user enters the array values during runtime.
public class NameComparator {
public static void main(String args[]) {
Scanner sn = new Scanner(System.in);
int n = sn.nextInt();
System.out.println("the array size is" + n);
int[] a = new int[7];
for (int i = 0; i >= a.length; i++) {
a[i] = sn.nextInt();
System.out.println("the value of a[i]" + a[i]);
}
sn.close();
System.out.println("array values are");
}
}
Here, I have got the array size from Scanner and then using for loop to get each array value, but I don't know why the array block hasn't executed. JVM just skips the for loop. Scanner works well
This:
for(int i=0;i>=a.length;i++)
should be:
for (int i = 0; i < a.length; i++)
You want to loop as long as i is smaller than a.length (i.e. the size of the array).
The for loop will be exited (or skipped) if the termination condition returns false. Since you're initializing i with 0, i>=a.length (i.e. 0 >= 7) will be instantly false.
Please note, that I've wrote i < a.length and not i <= a.length. The array size is currently set to 7, therefore the valid indices are from 0 to 6. You'll get an ArrayIndexOutOfBoundsException if you try to access index 7.
And you forgot to use your variable n to set the array size:
int[] a= new int[n];
There are few issues:
int[] a= new int[7];//<-- why hard coded?
int[] a= new int[n];// try, you already have array size from user
for(int i=0;i>=a.length;i++)//<-- condition fails, i is 0 for the first time
for(int i=0; i < a.length; i++)//try this
Take a close look at your for loop.
for(int i=0;i>=a.length;i++)
Notice that you are using a greater than sign.
Since i equals 0, the length of a would have to be 0 for this loop to run, and we already know that you declared a with a length of 7.
I would do some searching around because there's plenty of questions similar to this.
Regardless, you have a couple things incorrect. You prompt the user for an array size but then throw it out and use 7 instead:
int[] a= new int[7];
So, this should be:
int[] a= new int[n];
Second, your loop condition:
for(int i=0;i>=a.length;i++)
will be true as long as i is greater than a, which will never happen as long as a is a positive integer (because i starts at zero). So, if we're using less than, we should also remember that arrays are zero indexed, so if you input a value of 3, you only want to populate indexes 0, 1 and 2.
So, this should instead be:
for(int i=0;i < a.length;i++)
Finally, remember to prompt the user, even if this is just a learning exercise it's good practice. Put that all together and you'll get something like this:
public static void main(String args[])
{
Scanner sn=new Scanner(System.in);
System.out.println("Please enter an array size:" );
int n=sn.nextInt();
System.out.println("the array size is "+ n);
int[] a= new int[n];
System.out.println("Please enter your " + n + "array values:");
for(int i=0;i < a.length;i++)
{
a[i]= sn.nextInt();
System.out.println("The value of a[" + i + "] is " + a[i]);
}
sn.close();
System.out.println("Array values are " );
for (int arrayValue : a)
System.out.println(" " + arrayValue);
}
change the below code
for(int i=0;i>=a.length;i++) with for(int i=0;i<a.length;i++)
the condition should be < instead of >=
also use sn.hasNext() can simplify the solution.
This question already has answers here:
Enhanced 'for' loop causes an ArrayIndexOutOfBoundsException
(2 answers)
Closed 5 years ago.
Created the below code whilst playing with loops. The code below stores the Fibonacci values into an array and then prints them using for loops.
int [] numbers;
numbers = new int[25];
numbers[0] = 1;
numbers[1] = 1;
System.out.println("Initializing the array values");
for(int i = 2; i < numbers.length; i++)
{
numbers[i] = numbers[i-1] + numbers[i-2];
}
System.out.println("Printing out Fibonacci values");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i] + ", ");
}
The above code works fine. The first time I threw it together though, I used an enhanced for loop to print out the values (the second for loop in the code). This compiles fine, but when I run it I get the following;
Initializing the array values
Printing out Fibonacci values
1, 1, 2, 3, 8, 34, 377, 17711, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 34
at ArrayDemo.main(ArrayDemo.java:21)
I don't get what went wrong. Changing the second loop shouldn't change the values (you'll notice the fibonacci values are wrong (ie missing values)). And I don't get why a simple enhanced for loop would skip indexes. Now, this isn't really a big deal because this isn't for a project or anything, it just bugs me that I can't figure out why it's doing it. Any clues?
The enhanced for loop just looked like this;
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
i here is the elements in the array, not the indexes. It could be bigger than numbers.length.
For example, if numbers = {1,2,3,9} then i will be 1, 2, 3, 9. But its length is 4, so when you loop on the elements inside it, you're trying to do numbers[9] which exceeds its size.
You probably want to System.out.print(i + ", ");
for(int i = 0; i <= numbers.length; i++) should be
for(int i = 0; i < numbers.length; i++)
In java, arrays are 0 based indexing. It means that your first element should be accessed at the index 0 and obviously the last at the length of your array minus 1.
int tab[] = new int[3]; //tab of length 3
tab[0] = 11;
tab[1] = 24;
tab[2] = 5;
Here you access the last element by calling tab[2] or tab[tab.length-1], which is equivalent.
Apologies, that was just a mistake in the code I put up in the
question.
The problem is that you should do : System.out.print(i + ", ");
You should read this and this about enhanced for loop.
The for statement also has another form designed for iteration through
Collections and arrays This form is sometimes referred to as the
enhanced for statement, and can be used to make your loops more
compact and easy to read. To demonstrate, consider the following
array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array.
So item holds the current value from the numbers array and not the current index. That's why you get an IOOBE.
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
should be
for(int i : numbers)
{
System.out.print(i + ", ");
}
You don't need to use indexes in enhanced for-loop.
So I have an array from 0-4, that has 5 random integer values (ie 10,20,25,15,50). The program ask the user to enter an integer, lets say user enter 17. The program will check and with the 5 values from the array i have and print out numbers that are larger than what the user put in, in this case which is 17(I use a for loop to do this). I also want to print out the number of numbers that are larger than what the user enter, in this case 2 (numbers that are larger than 17). How do i do this? Do i write a for loop inside the first for loop?
int[] myArrays = new int[10,20,25,15,50];
int numEntered;
for (i = 0; i < myArrays.length; i++)
{
if (myArrays[i] > numEntered)
System.out.println(myArrays[i]);
}
Now how can I get the total numbers that are larger than what the user had input?
Just have a running total counter.
int counter = 0;
Then whenever you find a number that's larger than what the user had input, increment the counter using counter++;. Then after your for loop just print out the counter's value.
That should be enough information for you to solve the homework, without revealing too much.
You're on the right track; basically, the problem boils down to these items:
Looping through your array
Recording items greater than your specified value
Summing all items encountered greater than your specified value.
You can accomplish this all with a single loop of your array.
Why not just have an integer that you increment everytime you find a value greater than the user input?
int count=0;
for(int i=0; i<4; i++) {
if(myArrays[i] > numEntered) {
count++;
System.out.println(myArrays[i]);
}
}
System.out.println("found " + count + " values greater than " + numEntered);
Is a second for loop required? why? I'd do it like so..
//Take in the number to test.
public void islarger(int num){
int counter = 0;
int numbers[] = new int[5];
//loop through array
for(int x=0; x < array.length; ++x){
if(array[x] > num){
//If it meets the condition add it to the new array
numbers[y] = array[x];
++y;
}
}
//print our results.
System.out.println("There are " + counter " numbers larger than " + num + \n "They are...");
Arrays.toString(numbers);
}
I was wondering if there was a way to remove the default "0" value I get when I run the following code:
Scanner scan = new Scanner(System.in);
int [] x = new int[4];
for ( int i = 1; i < x.length; i++ )
{
System.out.println( "Enter number " + i + ": ");
x[i] = scan.nextInt();
}
Arrays.sort(x);
System.out.println(Arrays.toString(x));
}
The output is as follows
[0, i[1], i[2], i[3]]
Of course, all the array values here are actually the numbers entered into the console.
The code is WORKING. It successfully sorts any numbers into the correct order, however, there is always this nasty 0.
I'm not looking to remove ALL 0's (I want the user to be able to enter 0 and have it show up) - -I just don't want the default 0. Any ideas?
Array indexes in Java are 0-based, not 1-based. So start iterating from 0 instead of from 1 and you should be good:
for ( int i = 0; i < x.length; i++ )
for ( int i = 0; i < x.length; i++ )
When you allocate an array of size 4, you're allocating four ints: i[0],i[1],i[2], and i[3]. Because Java is fairly friendly, it sets all four of these to 0. So what you're seeing on the output is [i[0],i[1],i[2],i[3]] (in sorted order). The sort isn't adding the 0, it was already there. If you only want 3 numbers, then you should allocate an int[3] rather than an int[4]. And then, to go along with that, when you ask for number 1, store it in i[0]. The simplest change to do this would be to simply change the top line to
int [] x = new int[3];
and the later line to
x[i-1] = scan.nextInt();
The change suggested by other answers is the more common, one, though. Most programmers would have i go from 0 to 2 and then output i+1 when talking to the user.
The following code should work:
Scanner scan = new Scanner(System.in);
int[] x = new int[3];
for (int i = 0; i < x.length; i++)
{
System.out.println( "Enter number " + i + ": ");
x[i] = scan.nextInt();
}
Arrays.sort(x);
System.out.println(Arrays.toString(x));
The problem was, as others have pointed out, that your int i should start at 0, not 1.
I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.