This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
The program should print out values stored in an array of size 5 after the user has input the values.
Here is my code:
import java.util.Scanner;
public class Arrays_Qu1 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int arr[]= new int [5];
System.out.println("Enter a number");
int i;
for (i=0;i<arr.length;i++) {
arr[i]=sc.nextInt();
}
System.out.println(arr[i]);
}
}
After I enter the 5th value, the program does not terminate but instead throws:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
Because you are printing outside the loop and it is trying to print arr[5] which is out of bound of the array. The print should be in loop if you want to print each element.
int i;
for (i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
System.out.println(arr[i]); // to print each element
}
// value of i is now 5, so arr[i] is invalid
System.out.println(arr[i-1]); // to print last element
System.out.println(Arrays.toString(arr)); // to print whole array
You should access the last element of the array like:
System.out.println(arr[i - 1])
but I believe printing just the last element of an array is not what you want. So you should move line
System.out.println(arr[i])
in a for loop and it should be ok.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 months ago.
I have been writing the below mentioned code for the problem and it always shows me the error that my index is out of bounds for my length. I have tried printing the size and it is comparitively very large.
import java.util.*;
class Main {
public static void countingSort(int numbers[]) {
// int n = numbers.length - 2;
int largest=Integer.MIN_VALUE;
for (int i=0;i<numbers.length;i++){
largest=Math.max(largest,numbers[i]);
}
int count[]=new int[largest+1];
System.out.println(count.length+"= length\n");
for (int i=0;i<count.length;i++)
count[numbers[i]]++;
int j=0;
for (int i=0;i<count.length;i++){
while(count[i]>0){
numbers[j]=i;
j++;
count[i]--;
}
}
for(int i=0;i<numbers.length;i++)
System.out.println(numbers[i]);
}
public static void main(String args[]) {
int numbers[] ={5,8,7,19,25,4,2,3,1};
countingSort(numbers);
}
It is because your variable "numbers" only holds 9 values.
for (int i=0;i<count.length;i++)
count[numbers[i]]++;
This for loop will iterate depending on the size of your variable "count". In your case, the variable "count" will hold 26 values. It throws an error when the variable "numbers" is being accessed with an index beyond its size.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I have a simple for loop which prints the content of an integer array. It keeps throwing java.lang.ArrayIndexOutOfBoundsException exception. I have been scratching my head for couple of hours not knowing what is that I am doing wrong
public class ReverseArray {
public static void main(String[] args) {
int[] nums = {100,90,80,70,60,50,40,30,20,10};
for(int i = 10; i >= 0; i--){
System.out.print(nums[i] + " ");
}
}
}
The ArrayIndexOutOfBoundsException is thrown because you try to access the 11th element in a 10 element array.
Arrays use zero-based indexing, which means that when you do nums[0] you are trying to access the first element of the Array. So:
int[] nums = {100,90,80,70,60,50,40,30,20,10};
System.out.println(nums[0]);
will print
100
As a result of this, when you do nums[10], you are trying to access the 11th element, which doesn't exist. To fix this, you can start on index 9 instead of 10, like:
for(int i = 9; i >= 0; i--){ // "i" starts with a value of 9, so it works
System.out.print(nums[i] + " ");
}
Arrays in most programming language are indexed from 0 by default, so that means the first element which is 100 has an index of 0, so u access it as nums[0]. So from this u can realize that the last element in ur array has an index of 9 which is nums[9] ==10.
ur getting this error because ur trying to access the element at the 10th index even though ur array has elements only upto 9th index i.e nums[0] = 100, nums[1] = 90 ..... nums [9] = 10.
just change the i to 9 like this and it will work like a charm
public class ReverseArray {
public static void main(String[] args) {
int[] nums = {100,90,80,70,60,50,40,30,20,10};
for(int i = 9; i >= 0; i--){
System.out.print(nums[i] + " ");
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
import java.util.Scanner;
public class Java3{
int sumAll = 0;
int sumFive = 0;
int sumLast = 0;
int arr[];
int n;
void arraySum(int[] arr) {
for (int i = 0; i < arr.length; ++i) {
sumAll += arr[i];
if (i == 4)
sumFive += sumAll;
if (i >= (arr.length - 5))
sumLast += arr[i];
}
System.out.println("sum all = " + sumAll
+ " sum first five " + sumFive
+ " sum last five " + sumLast);
}
public static void main(String [] args) {
Java3 obj1 = new Java3();
Scanner scan1 = new Scanner(System.in);
System.out.println("enter the number of elements");
obj1.n = scan1.nextInt();
System.out.println("enter the elements");
for (int i = 0; i < obj1.n; ++i)
obj1.arr[i] = scan1.nextInt();
obj1.arraySum(obj1.arr);
}
}
The error I get
java.lang.NullPointerException
Errors on Null pointer exception has been asked and answered several times before, but I do not understand those explanations. Can anyone please explain it in a very easy manner. This is my code, and it is showing me the error at runtime.
This code is supposed accepts the size of an integer array followed by the integer array. Then calls a function which calculates:
sum of all digits
sum of first 5 digits
sum of last 5 digits
and prints each value in the console..
Seems like you are a beginner in coding, nullPointerException occurs whenever you are trying to access the value of an object that is not defined.
In your case you did not define your array. You should have defined your array as given below before trying to add values into the array this will remove the exception.
obj1.arr = new int[obj1.n];
Doing this will define your array in your object and with obj1.n it will initialize its size. Hope you can proceed from here. Please refer the usage of new and constructors in java.
The problem was you took the length of array as input , but you did not initialize the array . Please add this one line in the code:
obj1.n = scan1.nextInt();
obj1.arr = new int[obj1.n];
You should define your arr size. until you define the arr size it is null, and there is no memory will be allocated. You can avoid this by using ArrayList instead of array or define your arr with sum big number of size and asker user to enter the number of values less than that size.
int arr[] = new int[100];
define the array size once you know the value
obj1.arr = new int[obj1.n+1];
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
Hope this is better. I am writing a java assignment to implement a sorting technique. I used a scanner object within a loop to input user data to be sorted. However the scanner object continues to read data after array is filled and an index out of bounds error is shown. How do I deal with this.
public static void set1(int N)
{
int i,c,e,f;
double a,b;
int[] arr1 = new int[N];
int[] arr2 = new int[N];
System.out.println("Please enter numbers to be sorted");
for(i=0;i<=N;i++)
{
Scanner Secondin = new Scanner(System.in);
arr1[i] = Secondin.nextInt();
}
}
From 0 to and including N is too much. a new int[5] has slots 0, 1, 2, 3, and 4. That's 5 slots. arr1[5] is an ArrayIndexOutOfBoundsException because that'd be the 6th slot. Try for (int i = 0; i < N; i++) instead (note, < instead of <=).
Don't keep making scanners. Make 1 scanner, once, and keep using it.
Inside the for loop at the end, try this code:
if (i == N) {
break;
}
This will break out of the for loop as soon as you reach the limit = N.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
Here is my code to reverse the elements in an array:
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int i=0; i < n; i++){
arr[i] = in.nextInt();
}
int i=0;
int j=n-1;
int c;
while(i<j){
c=arr[i];
arr[i]=arr[j];
arr[j]=c;
i++;
j--;
}
System.out.println(arr[n]);
in.close();
}
}
The problem is my code is generating arrayIndexOutOfBound exception. How to remove it ?
Change,
System.out.println(arr[n]);
to:
System.out.println(Arrays.toString(arr));
System.out.println(arr[n]);
Here is the problem because there's no index "n"
n is the number of elements
You have to loop form 0 to n-1
for(int i =0;i < n;i++){
System.out.println(arr[i]);
}
your code works fine for reversing the array of elements but arrayIndexOutOfBound exception is raised due to System.out.println(arr[n]). Remember array index starts from zero.For n size array, the range will be [0,(n-1)] ie., if n=5 range will be 0 to 4.
for(int k=0;k<arr.length;k++)
{
System.out.println(arr[k]);
}