checking if Index out of Range with array - java

I have written a program with a lot of operations on arrays. How I can check if I out of range with array, because I go Run Time Error at SPOJ.

Without knowing any more detailed context, the basic approach as outlined by Jon Skeet in the comments is something like the following:
if (index < 0 || index >= array.length) {
//Index Out Of Range
}

There is no code to refer and see if you have gone out of range. Maybe you want to post your code for reference.
As long as your index is not of negative value and 1 value under the length of your array, you will be within bounds of your array.
For example an array of length 10, you have to minus 1 and able to call indexes between 0 - 9.
for(int x=0; x < yourArray.length; x++){
//this for loop will nicely loop without going out of bounds unless your
//loop body contains something that will trigger the error.
}

Related

why do my averages not print out the way they're supposed to? [duplicate]

for (int i = 0; i < reports.length; i++) {
Products[] products = reports[i].getDecisions;
for (int j = 0; j < products.length; j++) {
}
}
Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j
Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index.
It's defined in JLS §10.4, if you are interested in it.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
You can't do that as array index in Java starts from 0.
But you can access array with index 1 with little modifications.
Example:
Consider an integer array "a" with length n
for(int i=0;i<n;i++) {
System.out.println(a[i]);
}
This can be modified as:
int a[] = new int[n+1];
for(int i=1;i<n+1;i++) {
System.out.println(a[i]);
}
Just like in most languages arrays are indexed from 0. You better get used to it, there is no workaround.
Base Index of Java arrays is always 0. It cannot be changed to 1.
You can use pointers, to jump to a certain point of the array and start the array from there.
For example:
char str[20];
str={'H', 'E' ,'L' ,'L', 'O','W' ,'O ','R','L',' D'};
char *ptr;
*ptr=str[0];
//right now its pointing to the starting.
ptr=ptr+3;
//Now pointing at 3rd unit.
This doesn't work in every compiler.This is the closest thing that can be done for your question.
its all simple that in C , C++ , Java or etc.. the array index start from "0" only. and we can't change it. but sometimes in some Practice problems we are asked to use 1-indexed-based array, which we actually can't do that, so to tackle that, just leave 0th-index aside, and start using the array from 1th-index onwards, and while solving the situation always keep in mind that we have to never include or use that 0th-index in our operations.

Why is my int[] array loop out of bounds?

Warning: I am very new to Java and programming in general. I'll try to be as clear as possible.
I am attempting to take a simple integer (inputnumber), convert it to a string (temp), create a new int[] array (numberarray), and loop through this int[] array, starting from the last digit, and print out the name of the digit.
I am rather sure that the conversion from integer to String to int[] array was functional due to Eclipse debugging, but am stumped as to why I am getting an ArrayOutOfBounds message from Eclipse for such a simple for loop. Any clues as to what I am doing wrong is appreciated.
String temp = inputnumber.toString();
int[] numberarray = new int[temp.length()];
for (int i=0;i<temp.length();i++) {
numberarray[i] = temp.charAt(i);
}
for (int i=temp.length();i>0;i--) {
if (numberarray[i]==1) System.out.print("one.");
if (numberarray[i]==2) System.out.print("two.");
if (numberarray[i]==3) System.out.print("three.");
if (numberarray[i]==4) System.out.print("four.");
if (numberarray[i]==5) System.out.print("five.");
if (numberarray[i]==6) System.out.print("six.");
if (numberarray[i]==7) System.out.print("seven.");
if (numberarray[i]==8) System.out.print("eight.");
if (numberarray[i]==9) System.out.print("nine.");
if (numberarray[i]==0) System.out.print("zero");
}
The Eclipse error message I am getting is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at jt.Intermediate8.main(Intermediate8.java:44)
Arrays are 0-indexed in Java. This means the last value is at index NUMBER_OF_ELEMENTS - 1
Therefore, in your for loop, you should change
int i=temp.length() // this is last index + 1 (since we are starting from 0)
To:
int i=temp.length() - 1 // this is last index
Also, as #brso05 said, don't forget to change your loop-ending condition to i>=0 since the last value going backwards will be at index 0.
Your for loop:
for (int i = temp.length(); i >= 0; i--)
You're starting the loop at temp.length(). That's not a valid index. Perhaps you want temp.length()-1?
You should be doing temp.length() - 1. The reason is that the array starts with index 0 not 1 so the last element in an array is stored at the length - 1. If there are 10 elements then 0-9 are your indexes. Also change i>0 to i>=0 if you want to hit all elements.
for (int i=(temp.length() - 1);i>=0;i--) {

JavaArray Index out of Bounds exception w/ for loop

I am getting an array index out of bounds exception while iterating over an array through the for-loop. Can someone tell me why this is happening it I have set the boolean in the for-loop to be i
public static boolean verify(int [] seq ){
for (int i=0; i<seq.length; i++){
//If the number is even, the next number
//must the half the previous number
if (seq[i] %2==0){
if (seq[i+1] != (seq[i]/2)){
return false;
}
}
//If the number is positive, the next number
//must be 3 times + 1 the previous number
else if (seq[i] %2!=0){
if (seq[i+1] != ((seq[i])*3+1)){
return false;
}
}
}
}
The problem is when you access index i+1. If i is the last possible value (seq.length - 1), then i+1 is one beyond the end of the array, resulting in an ArrayIndexOutOfBoundsException.
Stop your for loop one iteration earlier by modifying your condition to be:
i < seq.length - 1
You will face exception for the maximum value of i bcoz you are increasing the value by 1 to find the index value.
if (seq[i] %2==0){
if (seq[i+1] != (seq[i]/2)){
---------------------^
return false;
}
}
You're trying to access position i+1 or the Array. Since your for loop goes until the last element, you'll try to access 1 position after the last element, what causes the Out Of Bounds exception.
You are iterating over all elements in the array, but checking element seq[i + 1] for i == seq.lenth - 1 will always cause the exception. The last number is fully constrained by your conditions, so no need to check it. Make your loop run as follows: for (int i=0; i <seq.length - 1; i++)
This:
if (seq[i+1] != (seq[i]/2)) {
cannot access an element beyond the end of the array, when i is seq.length - 1.
Another line like that is down in the else branch.
Its quite obvious , when you are passing an array (i.e. array contains 10 elements) and operating inside loop that correct.But when you are accessing seq[i+1] , there might be the you are accessing the index which is not available in the array.
When the i value reaches at 10 and you are trying to access i+1 , but this index is not in array (as we know array size is 10)
So , its caused this exception.
Hope it will help you.

bubble sort string array

I'm trying to use a bubble sort to alphabetize an array that I've read into a program. The code compiles without error but I get an Array Index Out Of Bounds Exception on my 'if' construct when I try to run the program. I have initialized int i to 0 to account for the first index of the array so I think my error is elsewhere. I'm not asking anyone to write code for me, just maybe a point in the right direction. Thanks for any help.
public static String[] bubbleSort(String[] inL)
{
String temp;
int i = 0, passNum;
for(passNum = 1; passNum <= (inL.length); i++) // controls passes through bubble sort
{
if(inL[i].compareToIgnoreCase(inL[i + 1]) < 0)
{
temp = inL[i];
inL[i] = inL[i + 1];
inL[i + 1] = temp;
}
}
return inL; // returns sorted array
} // end bubbleSort method
You compare passNum instead of i against the length of the array. Since passNum is never modified, the loop condition is always true, and i gets incremented until it exceeds the range of the array.
Even if this particular issue is resolved, you may still run into problems with off-by-one errors with your current implementation. Consider whether you should compare i against inL.length - 1.
You never increment passNum so i continues incrementing forever. Also, array indexing in Java is based at 0. That means that the largest valid index is inL.length - 1. Since the body of your loop accesses inL[i+1], you should arrange your code so that i never exceeds inL.length - 2. At a minimum, you should change <= to < in the for loop termination test. (However, the logic of your comparison and incrementing escapes me; you need to fix that as well.)
Array.length stores the total length of an array, starting counting at 1.
The first index in an array however is 0, meaning that the last index is length-1.
adjust your check in your for-loop to fix the error
Your problem is the passNum <= (inL.length) it should be passNum < (inL.length) due to 0 being the first index of an array in java

How I can index the array starting from 1 instead of zero?

for (int i = 0; i < reports.length; i++) {
Products[] products = reports[i].getDecisions;
for (int j = 0; j < products.length; j++) {
}
}
Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j
Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index.
It's defined in JLS §10.4, if you are interested in it.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
You can't do that as array index in Java starts from 0.
But you can access array with index 1 with little modifications.
Example:
Consider an integer array "a" with length n
for(int i=0;i<n;i++) {
System.out.println(a[i]);
}
This can be modified as:
int a[] = new int[n+1];
for(int i=1;i<n+1;i++) {
System.out.println(a[i]);
}
Just like in most languages arrays are indexed from 0. You better get used to it, there is no workaround.
Base Index of Java arrays is always 0. It cannot be changed to 1.
You can use pointers, to jump to a certain point of the array and start the array from there.
For example:
char str[20];
str={'H', 'E' ,'L' ,'L', 'O','W' ,'O ','R','L',' D'};
char *ptr;
*ptr=str[0];
//right now its pointing to the starting.
ptr=ptr+3;
//Now pointing at 3rd unit.
This doesn't work in every compiler.This is the closest thing that can be done for your question.
its all simple that in C , C++ , Java or etc.. the array index start from "0" only. and we can't change it. but sometimes in some Practice problems we are asked to use 1-indexed-based array, which we actually can't do that, so to tackle that, just leave 0th-index aside, and start using the array from 1th-index onwards, and while solving the situation always keep in mind that we have to never include or use that 0th-index in our operations.

Categories