ArrayIndexOutOfBoundException when entering > 5 [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
it works properly but when i enter value which is more then 5 it gives exception but not giving me output. If i enter 12 then output should be like this ( 4 , 5 , 1 , 2 , 3)
public static void main(String args[]) {
int[] a = { 1 , 2 , 3 , 4 , 5 };
int[] b = new int[5];
int j = 0,m = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter n:");
int n = sc.nextInt();
sc.nextLine();
m = n;
for(int i = n ; i < 5 ; i++) {
b[j] = a[i] - n;
System.out.println("" +b[j]);
j++;
}
for(int i = 0 ; i < n ; i++) {
b[j] = a[i] - a[i];
j++;
}
for(int k = 0 ; k < 5 ; k++) {
System.out.println("a["+k+"]:" +b[k]);
}

As suggested in the comments on your question, the issue is to do with trying to access an element in an array that is not present.
E.g.
int[] array = new int[5];
int boom = array[10]; // Throws the exception
(copied from What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?)
In your example, the problem occurs in the code here:
for(int i = 0 ; i < n ; i++) {
b[j] = a[i] - a[i];
j++;
}
The reason is that you set n to the integer that you pass in (in your example '12') and then loop over i, increasing it each time, while it is less than n.
So using an input of '12', this loop will repeat 12 times with i increasing in value from 0 to 11.
Inside the loop you then try to access the ith element in the a array; which only has 5 elements.
This is fine for the first 5 iterations of the loop (i == 0 ... i == 4), but on the 6th (i == 5) it will try to access an element in the array that is not present; hence the ArrayIndexOutOfBoundException
Hope that makes sense
(Also, note: in the future it's generally a good idea to include a stack trace along with an exception)

Related

"Find Missing & Repeating Number" unable to compile on hackerrank suppose to use array list only not simple array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
Encountered this program on hackerrank it was showing runtime error.
The relevant code block is shown below.
On simple array its working, but on lists its not working.
Lists are only accepted.
Question statement on hackerrank:
You are given a read-only array of N integers with values also in the range [1,N] both inclusive. Each integer appears exactly once except A which appears twice and B which is missing. The task is to find the repeating and missing numbers A and B where A repeats twice and B is missing.
Input Format
First line is the length of the array - n
Second line contains n integer that is elements of the array
Constraints
1 <= n <= 105
1 <= arr[i] <= n
Output Format
Print array of integers containing repeating and missing number respectively
Sample Input 0
3
3 1 3
Sample Output 0
3 2
Explanation 0
A = 3 , B = 2 Since 3 is appearing twice and 2 is missing
public static List<Integer> find_missing(List<Integer> arr) {
int i;
// Repeating number
for (i = 0; i < arr.size(); i++) {
int abs_val = Math.abs(arr.get(i));
if (arr.get(abs_val - 1) > 0)
arr.get(abs_val - 1) = -arr.get(abs_val - 1);
else
return abs_val;
}
//Missing number
for (i = 0; i < arr.size(); i++) {
if (arr.get(i) > 0)
return (i + 1);
}
}
first of all arr.get(abs_val - 1) = -arr.get(abs_val - 1); is wrong because it's the same as saying 5 = -3 , as lValue is indeed a value not a variable , use arr.set(index, value); instead .
also in your code , you are using Math.abs() which isn'y necessary because in the question , it's said :
1 <= n <= 105 1 <= arr[i] <= n
so the values of arr[i] will always be positive.
so I edited the whole code of yours as it has many logic problems,
so for finding repeated numbers , what I do is to loop over the list , get every element then see if there is any other similar elements in the same array.
for finding repeated number , I loop over the numbers from 1 to N where N is entered by the user as specified by the problem above and check if every number is there in the list or not.
edited version of the code :
package com.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Integer> example = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; i++)
{
example.add(scanner.nextInt());
}
List<Integer> result = find_missing(example, n);
for (Integer i : result)
System.out.print(i + " ");
}
public static List<Integer> find_missing(List<Integer> arr, int n) {
List<Integer> temp = new ArrayList<>();
int i;
// Repeating number
for (i = 0; i < arr.size(); i++) {
for (int j = i + 1; j < arr.size(); j++) {
if (arr.get(j).equals(arr.get(i))){
if (temp.contains(arr.get(j)))
break;
temp.add(arr.get(i));
break;
}
}
}
//Missing number
for (i = 1; i <= n; i++) {
if (!arr.contains(i))
temp.add(i);
}
return temp;
}
}
and here is some examples of the output test cases:

ArrayList IndexOutOfBoundsException using Scanner

I write a program in which the input is given by the user through scanner and if the input is even it will be added to the array list, otherwise it will be removed.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //maximum no of elements to entered in arrayList
int a = 2;
ArrayList<Integer> al = new ArrayList<Integer>();
for(int i = 0; i < n; i++)
{
al.add(sc.nextInt());
if(al.get(i) % 2 == 0)
{
al.remove(al.get(i));
}
}
But it gives run time exception as :
Exception in thread "main" IndexOutOfBounException: Index: 2, Size:
2
TestInput:
5
1 2 3 4 5
Please tell me what I am doing wrong and other alternatives for this program!
This is happening because say you input an even number as the first number. Now as per you code you will remove this element from the list. Now the list is empty, but in the next iteration you are again trying to fetch the index of an empty list, hence the IndexOutOfBounException.
Change the logic to as follows:
First store all the numbers in the list.
for (int i = 0; i < n; i++) {
al.add(sc.nextInt());
}
Once done remove the odd numbers.
al.removeIf(i -> i % 2 != 0);
Or even better, don't store the odd numbers at all :
for (int i = 0; i < n; i++) {
int num = sc.nextInt();
if (num % 2 == 0)
al.add(num);
}

Java calculate ISBN using for loop [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am still new to Java, this question like: An ISBN-10 (International Standard Book Number)
consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum,
which is calculated from the other nine digits using the following formula:
(d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 +
d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11
If the checksum is 10, the last digit is denoted as X according to the ISBN-10
convention. Write a program that prompts the user to enter the first 9 digits and
displays the 10-digit ISBN (including leading zeros). Your program should read
the input as an integer.
See my code below:
It is working but the result is not correct!
public static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.print("Enter first 9 digit numbers: ");
int[] arr = new int[9];
int checkSum = 0;
for (int i = 0 ; i < arr.length; i++)
{
arr[i] = input.nextInt();
checkSum = (arr[i] * i) % 11;
}
System.out.print("The ISBN-10 Number is " );
for(int j = 0 ; j < arr.length; j++)
{
System.out.print(arr[j]);
}
if(checkSum == 10)
{
System.out.println("x");
}
else
{
System.out.println(checkSum);
}
I just want to use loop, make my method works. , i know how to use method without loop.
well. for JAVA
an array index start from 0. and Max index is length - 1.
if the index is not within this range. an arrayoutofbounds exception will be thrown
The problem is not that you are doing int i = 1 instead of int i = 0. The problem is that you changed i < arr.length; to i <= arr.length;. Since arr.length is 9, your code is trying to refer to arr[9] but arr only has elements arr[0] through arr[8].
First, review how we use arrays...
int[] I = new int[3];
The above creates an array with 3 spots in it. After instantiating the array, each element is based off of a 0-index. You only have I[0], I[1], and I[2] available (note this is three numbers) and trying to access I[3] will throw the error that you encountered in your program above: ArrayIndexOutOfBoundsException.
That being said, your loop is trying to access arr[9]. The highest index you have in the array is arr[8], because despite the array having 9 elements in it, it's 0-indexed.
Assuming you MUST have i starting from 1 for a homework assignment or something, change your code to:
public static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.print("Enter first 9 digit numbers: ");
int[] arr = new int[9];
int checkSum = 0;
for (int i = 1 ; i <= arr.length; i++)
{
arr[i-1] = input.nextInt();
checkSum = (arr[i-1] * i) % 11;
}
System.out.print("The ISBN-10 Number is " );
for(int j = 1 ; j <= arr.length; j++)
{
System.out.print(arr[j-1]);
}
if(checkSum == 10)
{
System.out.println("x");
}
else
{
System.out.println(checkSum);
}
int[] arr = new int[9];
This means the array has 9 slots. And the numbering of those slots starts from 0. Thus,
arr[0] is the first slot
arr[1] is the second slot
The last slot would be arr[8]. But in the following code you are iterating till i is equal to 9 which does not exist.
for (int i = 1 ; i <= arr.length; i++)
{
arr[i] = input.nextInt();
checkSum = (arr[i] * (i+1)) % 11;
}
This results in the ArrayIndexOutOfBoundsException. Change for (int i = 1 ; i <= arr.length; i++) to for (int i = 0 ; i < arr.length; i++)

Outputing items from a list if not divisible by 2 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a code that creates and fill an array then converts it to a list.
// I made a scanner and an integer "input".
Scanner in = new Scanner(System.in);
int input = in.nextInt();
// I make input into an array
int[] ints = new int[input];
// I fill the array
for(int i = 0; i < ints.length; i++){
ints[i] = i + 1;
}
// transform it into a list
List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < ints.length; index++)
{
intList.add(ints[index]);
}
Now i want to output System.out.println(); every items whose index is not devisible by 2 (items with indexes: 1 3 5and so on).
Not divisible by 2 means num % 2 != 0, so you can do:
if(i % 2 != 0) {
System.out.println(whatever);
}
I am guessing you only have to add to the intList if the index is not divisible by 2.
for(int index = 0; index < ints.length; index++)
{
if(index % 2 != 0)
intList.add(ints[index]);
}
Then you can simply print the intList which will only have indexes such as: 1, 3, 5, ...
for(int i = 0; i < intList.size(); i++)
System.out.println(intList.get(i));
It looks like what you need is an if statement use with modulo operator.
For example like this:
if( index % 2 == 1 ) System.out.println( ints[ index ] );
public static void main(String []args){
ArrayList<Integer> s = new ArrayList<Integer>();
s.add(1);
s.add(2);
s.add(3);
s.add(4);
s.add(5);
for(Integer sx:s){
if(sx%2!=0){
System.out.println(sx);
}
}
}

2D array in java gives java.lang.ArrayIndexOutOfBoundsException

I am new to Java and i am using eclipse for its compilation. I have seen many forums but i am not able to get around this error. I am creating a program for my homework and this is a small section of that program which is giving weird error. Any help is appreciated.
Here is where i am getting error -> aTwoD[i][j] = 0; <- at Initialize2D.<init>(Initialize2D.java:19)
I am stuck on this for quite some time now.
:-(
What is did ->
public class Initialize2D
{
private int[][] aTwoD;
public Initialize2D (int N)
{
System.out.println("N = " +N);
int counter = 0;
aTwoD = new int[N][N];
int i = 1;
while( i <= N )
{
int j = 1;
while( j <= N )
{
System.out.println("counter = " +counter);
aTwoD[i][j] = 0;
System.out.println("aTwoD["+i+"]["+j+"] = " + aTwoD[i][j]);
j++;
counter++;
}
i++;
}
}
public static void main( String[] args)
{
Initialize2D TwoDArray = new Initialize2D(2);
}
}
index starts from 0 so <= would cause out of bound
Array indices in Java start at 0, and end at length - 1. They don't start at 1 and end at length as your code assumes.
change
while( j <= N )
to
while( j < N )
In java indexing of N size array goes from 0 to N-1 including.
Beware that you iterate over i and j with the condition i <= N, j <= N.
Arrays in Java are zero based, meaning that they range between: 0 ... N-1.
If you access them with N that will be out of their range.
Change your iterator from i <= N to i < N (same for j). That should do the trick.

Categories