Array Index Out Of Bounds Exception - java

The problem:
a program that updates a list of students’ grades after the end of drop period. The program should reads from the user number of students who dropped and their indexes, and then the program should copies the remaining student’s grades to new array. In addition, the program should display both the original and the updated list. [Hint: the new array must have suitable length equivalents to number of remaining students]
my code:
public class Q5{
static Scanner scan = new Scanner (System.in);
public static void main (String args[]){
double [] list={1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10};
System.out.println("enter number of students who dropped:");
int num=scan.nextInt();
double [] list2 = new double [num];
System.out.println("Enter index Of the student who dropped ");
for (int j=1 ; j<=num ; j++)
{
System.out.println("student" + j + ":");
int index=scan.nextInt();
list[index]=0;
}
int j=0;
for(int i=0; i<list.length ; i++)
if (list[i]!=0)
{
list2[j]=list[i];
j++;
}
System.out.print("The original list : " );
for(int i=0; i<list.length ; i++)
System.out.print(list[i] + " " );
System.out.print("remaining students " );
for(int i=0; i<list2.length ; i++)
System.out.print(list2[i] + " " );
}
}
what is the problem ? it is not working !!!
in Line 16 it says :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Q5.main(Q5.java:23)
how I can correct this

That's because of the size of your list2.
You shouldn't set its size to num, but rather to the size of the original list. Because the list2 is going to contain just as many elements as the original list. You need the num only to fetch that many inputs from the user and assign those indexes with the value 0.
double[] list2 = new double[list.length]; // This should be the size of your list2
If you don't need to keep the original size, then you need to subtract the num from the original size, as suggested by #Joetjah.
double[] list2 = new double[list.length - num]; // This should be the size of your list2

Pseudo-code:
You start of with 10 students. Say you want to drop 2 students. That means you set the list2 size to 2.
Next thing you do, is trying to add all the students (10) from list to list2. But, list2 is too small for this. Thus you get your Exception.
What you want, is this:
double [] list2 = new double [list.length - num];

Guess that problem with predefined array 'list'.
Step 1: Created the list with one of the initializing ways. Here the size is fixed.
Step 2: Took input from user : lets assume it is 11.
list doesn't need to contain the size given as input.

You initialize list2 with wrong size.
You get from the user number of dropped students and then try to put in list2 all the remaining students.
double [] list2 = new double [list.length - num];

Your code will fail if the value entered by user is out of bounds for the array :
int index=scan.nextInt();
list[index]=0; // This may fail. Value entered by the user may exceed the array length

Its working fine
import java.util.Scanner;
public class Q5 {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("enter number of students who dropped:");
int num = scan.nextInt();
double[] list2 = new double[num - 1]; // should be num-1
System.out.println("Enter index Of the student who dropped ");
for (int j = 0; j < num; j++) {
System.out.println("student" + j + ":");
int index = scan.nextInt();
list[index] = 0;
}
int j = 0;
for (int i = 0; i < num; i++) {
if (list[i] != 0) {
list2[j] = list[i];
j++;
}
}
System.out.print("The original list : ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.print("remaining students ");
for (int i = 0; i < list2.length; i++) {
System.out.print(list2[i] + " ");
}
}
}
output is
enter number of students who dropped:
2
Enter index Of the student who dropped
student0:
1
student1:
2
The original list : 1.0 0.0 0.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 remaining students 1.0

This will remove the exception you got. From next time you don't use static values.
Edit:
It is not a good practice to assign values to any variable by yourself. As the array is having size of 10. If user enters more than 10 students dropped then it will cause a problem.
import java.util.*;
public class Q5 {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("enter number of students who dropped:");
int num = scan.nextInt();
double[] list2 = new double[list.length-num]; // should be num-1
System.out.println("Enter index Of the student who dropped ");
for (int j = 0; j < num; j++) {
System.out.println("student" + j + ":");
int index = scan.nextInt();
list[index] = 0;
}
int j = 0;
for (int i = 0; i < list.length; i++) {
System.err.println(""+list[i]);
if (list[i] > 0) {
list2[j] = list[i];
j++;
}
}
System.out.print("The original list : ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.print("remaining students ");
for (int i = 0; i < list2.length; i++) {
System.out.print(list2[i] + " ");
}
}
}

Related

two arrays from user input and get an output of the common values of the two arrays

I'm still new to java and been trying to write code that takes two different arrays of common values and outputs the common values of both arrays but I keep getting the following error message:
Exception in thread "main" Your common values are: 0 Your common
values are: 0 Your common values are: 0 Your common values are: 0
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for
length 5 at HomworkTestingQ.main(HomworkTestingQ.java:18)
Scanner sc = new Scanner(System.in);{
int n = 5;
int m = 5;
int[] array1 = new int[m];
int[] array2 = new int[n];
System.out.println("Enter the first array: ");
n=sc.nextInt();
System.out.println("Enter the second array");
m=sc.nextInt();
for(int i = 0; i < array1.length; i++) {
for(int j = 0; i < array2.length; j++) {
if(array1[i] == array2[j]) {
System.out.println("Your common values are: " + array1[i+j] );
}
}
}
}
}
}
I fix your codes:
Scanner sc = new Scanner(System.in);
int n = 5;
int m = 5;
int[] array1 = new int[m];
int[] array2 = new int[n];
System.out.println("Enter the first array: ");
for (int i = 0; i < n; i++) {
array1[i] = sc.nextInt();
}
System.out.println("Enter the second array");
for (int i = 0; i < n; i++) {
array2[i] = sc.nextInt();
}
for (int item : array1) {
for (int value : array2) {
if (item == value) {
System.out.println("Your common values are: " + item);
}
}
}
I believe the issue is that you're adding the array iterators here:
array1[i+j]
The i+j is adding to be more than the length of array1.
An aside, your arrays aren't being populated as I think you expect based on:
System.out.println("Enter the first array: ");
n=sc.nextInt();
System.out.println("Enter the second array");
m=sc.nextInt();
I'm just speculating there perhaps you have more to do there down the line.
You don't need to add up the indices..
Since array1[i] is equal to array2[j], print any one of them:
for(int i=0;i<array1.length;i++){
for(int j=i+1;j<array2.length;j++){
if(array1[i]==array2[j]) int commonValue = array1[i];
return commonValue; // or print it
}
}
FIRST PROBLEM
The size of the array won't change when you scan the value of m and n because java is pass by value and the size of the array is the value, not the variable.
So you should do something like-
int m = scanner.nextInt();
int[] arr = new int[m];
SECOND PROBLEM
System.out.println("Your common values are: " + array1[i+j] );
This will go out of bounds, perhaps you should do-
System.out.println("Your common values are: " + array1[i] );

Adding corresponding elements of two arrays into third array

I am trying to let the user input the number of elements arrA and arrB should have and also making the user choose the int number they want for each corresponding element in both, arrA and arrB. Then, creating the third arrC with the sum of the corresponding elements in arrA and arrB and then printing arrA, arrB and arrC.
The output should look like this:
Input the length: 5
Enter a value for first array, position 0: 1
Enter a value for first array, position 1: 6
Enter a value for first array, position 2: 13
Enter a value for first array, position 3: -3
Enter a value for first array, position 4: 8
Enter a value for second array, position 0: 9
Enter a value for second array, position 1: -4
Enter a value for second array, position 2: 1
Enter a value for second array, position 3: 65
Enter a value for second array, position 4: 18
first: 1 6 13 -3 8
second: 9 -4 1 65 18
result: 10 2 14 62 26
This is the code I have written so far and I need help as to how would i use scanner to let the user choose the input length of arrA and arrB and the elements in arrA and arrB. This is what the code looks like so far :-
class ArrayArithmetic
{
public static void main ( String[] args )
{
int[] arrA = { 11, -27, 89, 17};
int[] arrB = {-3, 24, -9, -16};
int[] sum = { 0, 0, 0, 0};
for(int i = 0; i < arrA.length - 1; i++)
{
for(int j = 0; i < arrB.length - 1; i++)
{
sum[i] = arrA[i] + arrB[i];
}
}
System.out.println("sum: " + sum[0]+"," + sum[1] + "," + sum[2] + "," + sum[3] );
}
}
Lets suppose you have only 2 arrays to make it easy and don't nest loops, when you understand this pieces of code you can wrap all the method with a new loop and create infinite arrays to sum to result if you want... but you have to understand the basics first:
Create a Scanner and ask user for the lenght of the arrays:
Scanner sc = new Scanner(System.in);
// ask user!
System.out.println("Input the length:");
int arrayLength = in.nextInt();
Create the arrays with given lenght
int[] fistArray = new int[arrayLength];
int[] secondArray = new int[arrayLength];
int[] totals = new int[arrayLength];
Fill fist array iterating positions from 0 to number entered by user:
for (int i = 0; i < arrayLength; i ++) {
System.out.println("Enter a value for first array, position "+ i);
try {
firstArray[i] = Integer.parseInt(sc.nextLine());
} catch (Exception e) {
System.out.println("Not a valid number!!!);
i --;
}
}
Fill second array iterating positions from 0 to number entered by user and get the sum of each pos:
for (int i = 0; i < in.nextInt(); i ++) {
System.out.println("Enter a value for second array, position "+ i);
try {
secondArray[i] = Integer.parseInt(sc.nextLine());
totals[i] = fistArray[i] + secondArray[i];
} catch (Exception e) {
System.out.println("Not a valid number!!!);
i --;
}
}
And print the results:
System.out.println(Arrays.toString(firstArray));
System.out.println(Arrays.toString(secondArray));
System.out.println(Arrays.toString(totalsArray));
Finally, don't forget to close your Scanner to avoid memory leaks as pointed drgPP so:
sc.close();
The following code should do as you wanted:
import java.util.*;
class ArrayArithmetic
{
public static void main ( String[] args )
{
Scanner in = new Scanner(System.in);
System.out.print("Input the length ");
int len = in.nextInt();
int[] arrA = new int[len];
int[] arrB = new int[len];
int[] sum = new int[len];
for (int i = 0; i < len; i++){
System.out.print("Enter a value for first array, position " + i + ": ");
arrA[i] = in.nextInt();
}
for (int i = 0; i < len; i++){
System.out.print("Enter a value for second array, position " + i + ": ");
arrB[i] = in.nextInt();
}
for(int i = 0; i < arrA.length; i++)
{
for(int j = 0; i < arrB.length; i++)
{
sum[i] = arrA[i] + arrB[i];
}
}
System.out.println("sum: " + sum[0]+"," + sum[1] + "," + sum[2] + "," + sum[3] );
} }
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Length of arrays: ");
try {
//Initializing length of array
int length = sc.nextInt();
//Constructing our arrays based on length
int[] arrA = new int[length];
int[] arrB = new int[length];
int[] arrSum = new int[length];
//Populating our array A via a loop
for (int i=0; i<arrA.length; i++) {
System.out.println("Values for arrA at index: "+i);
int value = sc.nextInt();
arrA[i]=value;
}
//Populating our array B via a loop
for (int i=0; i<arrB.length; i++) {
System.out.println("Values for arrB at index: "+i);
int value = sc.nextInt();
arrB[i]=value;
}
//Call the method to calcualte our sum which will be in sum array
arrSum = makeSum(arrA, arrB, length);
System.out.println(Arrays.toString(arrSum));
} catch (Exception e) {
e.printStackTrace();
} finally {
sc.close();
}
}
// Method to calculate our Sum Array based on the length and the Array A and B
public static int[] makeSum (int[] arrA, int[] arrB, int length) {
int[] arrSum = new int[length];
for (int i=0; i<arrA.length; i++) {
for (int j=0; j<arrB.length; j++) {
arrSum[j]=arrA[i]+arrB[j];
}
}
return arrSum;
}
Perhaps this is your question:
Scanner scan = new Scanner(System.in);
System.out.println("Enter size: ");
int size =scan.nextInt();
Integer[] arrA = new Integer[size];
ArrayList<Integer> arrB = new ArrayList<Integer>(size);

How do I get the right output for this array?

I'm trying to obtain specific outputs for an array. The array's been put in a while loop to continue to set up new arrays until it reaches its counter. The counter and the amount of elements in each array line up, but once I try to get my output, it doesn't work out. What should I fix to work it out?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i; int j; int n; int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while(count < n) //counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);//represents how many numbers within a line
count++;
for(j = 0; j < numbers.length; j++) //numbers within line
{
numbers[j] = input.nextInt();}
for(int p = 0; p < numbers.length - 1; p++) //prints specific values in line
{
numbers[p] = numbers[numbers.length - 1 ];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers)); }
input.close();}
} }
First User Input:
3
2
10
1
Expected Output:
10
Instead, I get 1. What I wanted to do was subtract the last element of the array from the rest of the array to get the desired output. This includes the last element as well.
code works fine, just need to close scanner outside while. Fix the brackets.
input.close(); outside while loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i;
int j;
int n;
int u;
int count = 0;
n = input.nextInt();
System.out.println("Times repeated: " + n);
while (count < n) // counter represents amount of times loop will occur
{
i = input.nextInt();
int[] numbers = new int[i];
System.out.println("Length of Array: " + i);// represents how many numbers within a line
count++;
for (j = 0 ; j < numbers.length ; j++) // numbers within line
{
numbers[j] = input.nextInt();
}
for (int p = 0 ; p < numbers.length - 1 ; p++) // prints specific values in line
{
numbers[p] = numbers[numbers.length - 1];
p = numbers[p];
System.out.println(p);
System.out.println(Arrays.toString(numbers));
}
}
input.close();
}
output
2
Times repeated: 2
2
Length of Array: 2
1
2
2
[2, 2]
2
Length of Array: 2
1
2
2
[2, 2]

Pulling distinct values from a array in java

Have a program where the user inputs 10 int values into the array. Lastly I need to pull out the distinct values and display them. Added my second for loop which would determine if the the value is distinct (i.e. meaning if the number appears multiple times it is only displayed once).
For instance, let say I pass in the numbers: 1, 2, 3, 2, 1, 6, 3, 4, 5, 2 the distinct array should only contain numbers {1, 2, 3, 6, 4, 5}
import java.util.Scanner;
import java.io.*;
public class ArrayDistinct {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
// Create arrays & variables
int arrayLength = 10;
int[] numbers = new int[arrayLength];
int[] distinctArray = new int[arrayLength];
int count = 0;
System.out.println("Program starting...");
System.out.print("Please enter in " + numbers.length + " numbers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
for (int i = 0; i < numbers.length; i++) {
int temp = numbers[i];
int tempTwo = numbers[i + 1];
if (tempTwo == temp) {
count++;
distinctArray[i] = temp;
}
}
// Print out results
} // end main
} // end class
Try this :
Set<Integer> uniqueNumbers = new HashSet<Integer>(Arrays.asList(numbers));
uniqueNumbers will contain only unique values
In Java 8
Stream< T > distinct()
Returns a stream consisting of the distinct elements (according to
Object.equals(Object)) of this stream. For ordered streams, the
selection of distinct elements is stable (for duplicated elements, the
element appearing first in the encounter order is preserved.) For
unordered streams, no stability guarantees are made.
Code:
Integer[] array = new Integer[]{5, 10, 20, 58, 10};
Stream.of(array)
.distinct()
.forEach(i -> System.out.print(" " + i));
Output:
5,10,20,58
Read More About distinct function
Try this code.. it will work
package Exercises;
import java.util.Scanner;
public class E5Second
{
public static void main(String[] args)
{
Scanner In = new Scanner(System.in);
int [] number = new int [10];
fillArr(number);
boolean [] distinct = new boolean [10];
int count = 0;
for (int i = 0; i < number.length; i++)
{
if (isThere(number,i) == false)
{
distinct[i] = true;
count++;
}
}
System.out.println("\nThe number of distinct numbers is " + count);
System.out.print("The distinct numbers are: ");
displayDistinct(number, distinct);
}
public static void fillArr(int [] number)
{
Scanner In = new Scanner(System.in);
System.out.print("Enter ten integers ");
for (int i = 0; i < number.length; i++)
number[i] = In.nextInt();
}
public static boolean isThere(int [] number, int i)
{
for (int j = 0; j < i; j++)
if(number[i] == number[j])
return true;
return false;
}
public static void displayDistinct(int [] number, boolean [] distinct)
{
for (int i = 0; i < distinct.length; i++)
if (distinct[i])
System.out.print(number[i] + " ");
}
}
One possible logic: If you're supposed to only sort out "unique" numbers, then you'll want to test each number as it's entered and added to the first array, and loop through the array and see if it's equal to any of the numbers already there; if not, add it to the "unique" array.
Sets in java doesn't allow duplicates:
Integer[] array = new Integer[]{5, 10, 20, 58, 10};
HashSet<Integer> uniques = new HashSet<>(Arrays.asList(array));
That's it.
Something like this should work for you:
Scanner input = new Scanner(System.in);
// Create arrays & variables
int arrayLength = 10;
int[] numbers = new int[arrayLength];
int[] distinctArray = new int[arrayLength];
int count = 0;
Set<Integer> set = new HashSet<Integer>();
System.out.println("Program starting...");
System.out.print("Please enter in " + numbers.length + " numbers: ");
for (int i = 0; i < numbers.length; i++) {
set.add(input.nextInt());
}
for(Integer i : set)
{
System.out.println("" + i);
}
This will only add unique values to the set.
int a[] = { 2, 4, 5, 3, 3, 3, 4, 6 };
int flag = 0;
for (int i = 0; i < a.length; i++)
{
flag = 0;
for (int j = i + 1; j < a.length; j++)
{
if (a[i] == a[j])
{
flag = 1;
}
}
if (flag == 0)
{
System.out.println(a[i]);
}
}

Trouble merging two sorted user-inputed arrays

Writing a code that should read two already sorted arrays from a user of the user's defined length, then sort them into one still-sorted list. For some reason I can't get it to sort past the first three digits? It looks like it might be something really simple that I'm missing but I've been fiddling with it for a while and not finding anything. Any ideas?
Sample Run:
How long are the lists?: 3
Enter list A:
1: 1.0
2: 2.0
3: 3.0
Enter list B:
1: 2.0
2: 3.0
3: 4.0
Merged List: 1.0, 2.0, 2.0, 3.0, 3.0, 4.0
code:
import java.util.Scanner; //import scanner
public class project2 {
public static void main (String[] args){
Scanner input = new Scanner(System.in); //scanner for input
int a = 0;
System.out.println("How long are the lists? ");
System.out.print("(The lists should be the same length): ");
a = input.nextInt();
double [] lista = new double [a]; //create array
double [] listb = new double [a]; //create array
int count=1;
System.out.println("Enter numbers for list A:");
for(int j = 0; j < a ; j++){ //user input numbers loop into array "list"
System.out.print(count + ": ");
lista[j] = input.nextDouble();
count++;
}
int acount = 1;
System.out.println("Enter numbers for list B:");
for(int j = 0; j < a ; j++){ //user input numbers loop into array "list"
System.out.print(acount + ": ");
listb[j] = input.nextDouble();
acount++;
}
System.out.println(); // print the original lista inputed by user
System.out.print("Your list A: ");
for(int j=0; j<a; j++){
System.out.print(lista[j] + " ");
}
System.out.println(); // print the original listb inputed by user
System.out.print("Your list B: ");
for(int j=0; j<a; j++){
System.out.print(listb[j] + " ");
}
project2.merge(lista, listb);
System.out.println(); // print the new merged listc
System.out.print("Merged List: ");
for(int j=0; j<a; j++){
System.out.print(project2.merge(lista, listb)[j] + ", ");
}
}
public static double [] merge ( double [] list1, double [] list2){
double [] listc = new double [list1.length + list2.length]; //create array
int i = 0, j = 0, k = 0;
while (i < list1.length && j < list2.length)
{
if (list1[i] < list2[j])
{
listc[k] = list1[i];
i++;
}
else
{
listc[k] = list2[j];
j++;
}
k++;
}
while (i < list1.length)
{
listc[k] = list1[i];
i++;
k++;
}
while (j < list2.length)
{
listc[k] = list2[j];
j++;
k++;
}
return listc;
}
}
You are merging two arrays of length a, into an array of length 2 * a, but you only print out the first a numbers. Modify your for loop condition that prints out the merged array:
for(int j=0; j< 2*a; j++){
Also, every time you call merge, you merge the arrays again. Just merge it once, then refer to the array when printing the contents. This version uses the new merged array's length to stop the loop.
double[] listc = project2.merge(lista, listb);
System.out.println(); // print the new merged listc
System.out.print("Merged List: ");
for(int j=0; j < listc.length; j++){
System.out.print(merged[j] + ", ");
}
Hint: Since you are merging two sorted lists into one (output) sorted list, consider a loop that you execute for the size of the output list .. and put into the next output slot the next appropriate value from each of the two input lists.
Inside that loop, what would you want to compare to see which value you get next?
How would you handle exhausting one list before the other?
How can you generalize your program so the two input lists do not need to be the same length?
(no code for homework)
Why do you not just use the JDK-method java.util.Arrays#sort(double[]) instead of reinventing the wheel?

Categories