I have the following bit of code that I am having some difficulty with. My expectation for output should be the applicant # with their correlated test score. The first position of both arrays is for the answer key. Not quite sure where I am going wrong with this, but any help would be appreciated.
public class applicantCheck
{
//* main method
public static void main(String[] args)
{
int i = 0, j = 0, correct;
//* initialization of applicant id's and answers
int[] appID = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
char[][] appAnswers = { {'N','Y','N','N','Y','N','N','Y','N','Y'},
{'N','Y','Y','N','Y','N','Y','Y','N','Y'},
{'N','Y','N','Y','N','Y','Y','Y','N','N'},
{'N','Y','Y','N','Y','Y','Y','Y','Y','Y'},
{'Y','Y','N','N','Y','N','N','Y','Y','Y'},
{'Y','Y','N','Y','Y','Y','N','N','T','N'},
{'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y'},
{'N','Y','N','N','N','Y','N','Y','N','Y'},
{'Y','N','Y','N','Y','N','Y','N','Y','N'},
{'Y','Y','Y','N','N','Y','Y','N','Y','N'},
{'N','N','N','N','N','N','N','N','N','N'},
{'Y','N','Y','Y','N','Y','Y','N','Y','N'},
{'N','Y','N','N','Y','Y','N','N','N','Y'},
{'N','Y','N','Y','N','Y','N','Y','N','Y'},
{'Y','N','Y','N','Y','Y','N','Y','N','Y'} };
System.out.println("Applicant #\t\tMark (out of " + appAnswers[i].length + ")");
for (i = 1; i < appID.length; i++)
{
System.out.printf("%-9d", appID[i]);
correct = 0;
for (j = 0; j <= i; j++)
{
if (appAnswers[0][j] == appAnswers[i][j])
{
correct++;
}
}
System.out.printf("%10d\n", correct);
} // end of for loop
System.out.println();
} // end of main
} // end of file
The output is:
--------------------Configuration: <Default>--------------------
Applicant # Mark (out of 10)
1 2
2 3
3 3
4 4
5 3
6 2
7 6
8 3
9 2
10 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at applicantCheck.main(applicantCheck.java:36)
Don't want to solve the problem for you since it is homework, but here's a hint.
Array indexes go from 0 to the number of elements -1. Check your loop to make sure it doesn't go past the end.
I haven't verified if this is the problem, but it's a red-flag:
for (j = 0; j <= i; j++)
Did you mean this?
for (j = 0; j < 10; j++)
You only have 10 in each row. But i goes up to 14 or so. Therefore j will go out of bounds.
Instead of
for (j = 0; j <= i; j++)
try
for (j = 0; j < 10; j++)
since the array is always the same length.
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.
This post was edited and submitted for review 3 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I'm not new at Java, but I'm in JUnit. I'm having a problem with a simple for loop. I'm ordering array elements with bubble sorting, but I don't know why the two last elements disappear during the loop. I know it will be a little tiny thing, but I can't find the mistake. Could you help me, please?
This is my class:
package exercise5;
public class Ejercicio5 {
public static int[] sort(int[] arrayNums) {
// array that I have tried: {6,5,8,3,7,1}; [6]
System.out.println("size: " + arrayNums.length);
for (int j = 0; j < arrayNums.length; j++) {
System.out.println("j:" + j);
if (arrayNums[j] > arrayNums[j + 1]) {
System.out.println("entra");
int numGuardado = arrayNums[j + 1];
arrayNums[j + 1] = arrayNums[j];
arrayNums[j] = numGuardado;
}
print(arrayNums);
}
return arrayNums;
}
public static void print(int[] arrayParaImprimir) {
System.out.println("Array:");
for (int j = 0; j < arrayParaImprimir.length; j++) {
if (j != arrayParaImprimir.length - 1) {
System.out.print(arrayParaImprimir[j] + ", ");
} else {
System.out.print(arrayParaImprimir[j] + "\n");
}
}
}
}
My TestClass with JUnit5:
package exercise5;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import junit.framework.TestCase;
public class Ejercicio5Test extends TestCase{
#Test
public void resultadoCorrecto(){
int[] correct = {1,3,5,6,7,8};
int[] array = {6,5,8,3,7,1};
int[] result = Ejercicio5.sort(array);
Assert.assertArrayEquals(result, correct);
}
#Test
public void resultadoIncorrecto(){
int[] correct = {1,3,5,6};
int[] array = {3,5,6,1};
int[] result = Ejercicio5.sort(array);
Assert.assertArrayEquals(result, correct);
}
}
When j is equal to 4, the ordering is doing: 5, 6, 3, 7, 1, 8
but when j passed to 5, two elements disappear.
In addition, in my Test class there are only two methods, but, when I run it, it recognises one more and give me an error:
This is the array that I have tried {1,3,5,6,7,8} and this is that I expected {5,6,3,7,1,8} with 6 of array's size, not element disappearing.
enter image description here
This is the output in console. NOT ArrayIndexOutOfBounds. Only disappear 2 elements, and the size changes, not throwing any exceptions:
size: 6
j:0
entra
Array:
5, 6, 8, 3, 7, 1
j:1
Array:
5, 6, 8, 3, 7, 1
j:2
entra
Array:
5, 6, 3, 8, 7, 1
j:3
entra
Array:
5, 6, 3, 7, 8, 1
j:4
entra
Array:
5, 6, 3, 7, 1, 8
j:5
size: 4
j:0
Array:
3, 5, 6, 1
j:1
Array:
3, 5, 6, 1
j:2
entra
Array:
3, 5, 1, 6
j:3
for (int j = 0; j < arrayNums.length; j++) {
This loops for every number in the input. Then you..
if (arrayNums[j] > arrayNums[j + 1]) {
Compare this to the next number in the input. On the last loop, you are therefore comparing the last number (arrayNums[j]) with the.. number after that. Which doesn't exist, hence, ArrayIndexOutOfBoundsEx.
You want to loop one fewer.
You missed one loop here is the correct code -
public class Ejercicio5 {
//you don't need to return as it modifies exiting array
public static void sort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
// swap arr[j+1] and arr[j]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
/* Prints the array */
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
int[] array = {6,5,8,3,7,1};
Ejercicio5.sort(array);
System.out.println("Sorted array");
Ejercicio5.printArray(array);
}
}
output - Sorted array 1 3 5 6 7 8
and your testcases should work now with minor changes
If you run the JUnit test, it runs all the methods annotated by #Test.
Your output exactly reflects the 2 calls of your sort function, first from resultadoCorrecto() to line "j:5", second call from resultadoIncorrecto(), what outputs lines after that (from "size: 4").
So nothing has disappeared.
resultadoCorrecto() calls sort function with an array size of 6.
resultadoIncorrecto() calls sort function with an array size of 4.
Your bubble sort problem:
The for loop must go until index < length-1.
You must bubbling up all the bubbles with another for cycle around. (See Sagar Kale's answer.)
I'm trying to convert command line arguments in an int array, but it appears a "0" in the end of the array. How can I fix it?
import java.util.Arrays;
public static void main(String[] args){
int[] game = new int[9];
for (int i = 0; i <= 8; i++)
game[i] = Integer.parseInt(args[i]);
System.out.println(Arrays.toString(game));
}
Example run:
$ java edu.kit.informatik.TicTacToe 5 6 4 1 2 3 7 8 9
[5, 6, 4, 1, 2, 3, 7, 8, 9, 0]
I have tested your code, there aren't '0' at the end of the list. I recommend you that use args.length for handling variety arguments count.
public static void main(String[] args) {
int[] game = new int[args.length];
for (int i = 0; i < args.length; i++)
game[i] = Integer.parseInt(args[i]);
System.out.println(Arrays.toString(game));
}
When you create a new int[] array in Java, its initial contents are all zeros. If you then fill it up with fewer numbers than it is long, you'll see the zeros that have not been overwritten at the end.
// creating an array of size 10
int[] array = new int[10];
// only filling up the first 8 elements
for (int i = 1; i <= 8; i++) {
array[i-1] = i;
}
// printing the full array
for (int i = 0; i < array.length; i++) {
System.out.print(i + " ");
}
System.out.println();
This will output:
1 2 3 4 5 6 7 8 0 0
The last two zeros are just the elements that have not been set to anything else.
I have two arrays of different sizes that I am trying to loop through and perform calculations on, but I am ending up with incorrect outputs.
Here are the arrays:
int[] array1 = [5, 10, 2]
int[] array2 = [11, 23, 4, 6, 5, 8, 9]
int[] array1 = {5, 10, 2};
int[] array2 = {11, 23, 4, 6, 5, 8, 9};
ArrayList<Integer> calculationsArray = new ArrayList<Integer>();
int calculations = 0;
for(int i = 0; i < array1.length; i++) {
for(int j = 0; j < array2.length; j++) {
calculations = ((array1[i] + array2[j]) % 10);
}
calculationsArray.add(calculations);
}
I expect the output of [6, 3, 6, 1, 0, 8, 1]. Example calculations for 4 loops would be:
(11 + 5) % 10 = 6
(23 + 10) % 10 = 3
(4 + 2) % 10 = 6
(6 + 5) % 10 = 1
But the actual output is: [4, 9, 1]
Let's first talk about why you're seeing what you're seeing.
I've reposted your code here, with the indentation changed to reflect the nesting:
for(int i = 0; i < array1.length; i++) {
for(int j = 0; j < array2.length; j++) { // <--- This loop
calculations = ((array1[i] + array2[j]) % 10);
}
calculationsArray.add(calculations);
}
Let's take the inner loop, the one that I've marked above. Notice that on each iteration of the loop, you set calculations to a new value. This overwrites the value that was computed earlier, so that when the inner loop finishes running, the value of calculations will be equal to the last value that's computed in that loop. And that accounts for what you're actually seeing, because
when i = 0, the inner loop's last calculation is (array1[0] + array2[6]) % 10, which is (5 + 9) % 10 = 4,
when i = 1, the inner loop's last calculation is (array1[1] + array2[6]) % 10, which is (10 + 9) % 10 = 9,
when i = 2, the inner loop's last calculation is (array1[2] + array2[6]) % 10, which is (2 + 9) % 10 = 1.
And hey, look! There's your [4, 9, 1] that you're seeing.
The next question is how to go about fixing this. The major issue I believe that you're running into here is the fact that doubly-nested loops probably isn't the way to go here. Specifically, a double for loop here will run array1.length × array2.length times, which is way more than the number of times that you need it to run.
So a first question - how many times should the loop run? Well, you want your output array to have the length of the longer of the two input arrays, which is Math.max(array1.length, array2.length) times. Could you make a single loop that counts up to that number?
You then need to handle the fact that your loop may need to cycle through each input array multiple times. In the example you've given, you'll read the values of array1 multiple times because array2 is longer, but you just as easily could have had to read the values of array2 multiple times if array1 were longer.
As a hint for how to do this, see if you can use the mod operator % to wrap around when the indices get too big.
Hope this helps!
What about somenthing like (not optimized):
ArrayList<Integer> calculationsArray = new ArrayList<Integer>();
int calculations = 0;
int j = 0;
while (j < array2.size()) {
for (int i = 0; i < array1.size(); i++) {
calculations = ((array1.get(i) + array2.get(j)) % 10);
calculationsArray.add(calculations);
}
j++;
}
This question already has answers here:
ArrayIndexOutOfBounds on enhanced for loop
(2 answers)
Closed 6 years ago.
I'm going through an example on Code Wars. Essentially, taking a number, finding the multiples of 3 and 5 and adding these together. Assuming the number is 10, we'll have 3,5,6,9.
I am at the point where I want to add the multiples together (the foreach loop at the bottom) but I keep getting an OutOfBoundsException. I don't understand how it is reaching index 5! Can someone please explain this to me?
I've seen a few examples of this error on here but can't checking through these I've not been able to resolve the issue, sorry.
package Test;
import java.util.ArrayList;
import java.util.List;
public class MultiplesOf3And5 {
public static void main(String[] args) {
int number = 10;
int total = 0;
List<Integer> multiples = new ArrayList<Integer>();
for (int i = 1; i < number; i++) {
if (i % 3 == 0) {
System.out.println(i + " is a multiple of 3");
multiples.add(i);
} else if (i % 5 == 0) {
System.out.println(i + " is a multiple of 5");
multiples.add(i);
}
}
for (int j : multiples){
System.out.println(multiples.get(j));
System.out.println(multiples.toString());
total += multiples.get(j);
}
System.out.println(total);
}
}
for-each loop iterates the values of your List multiples, you used each value of the List as index by accident. Fix it as below:
for (int j : multiples){
System.out.println(j);
System.out.println(multiples.toString());
total += j;
}
The output is:
3 is a multiple of 3
5 is a multiple of 5
6 is a multiple of 3
9 is a multiple of 3
3
[3, 5, 6, 9]
5
[3, 5, 6, 9]
6
[3, 5, 6, 9]
9
[3, 5, 6, 9]
23
System.out.println(j);
You are trying to get the jth object out of the list, but the you are iterating over the values not the index.
your ArrayList have = 3,6,9(factor of 3) & 5(factor of 5)
so total 4-value reside into ArrayList.
now you are trying to get value from ArrayList not based upon index like 0,1,2,3...
but you are fetching value from ArryList likewise, multiples.get(3), .get(6)... etc.
that's why you get error, like ArrayIndexOutOfBoundException.
Better to follow this way,
for (int j : multiples){
System.out.println(j);
System.out.println(multiples.toString()); // not required but you want then remain it is likewise... or else remove this line
total += j;
}
Your error is occurring because your for loop is assigning the actual values of your array list. Try this:
for(int j = 0, j < multiples.size(), j++) {
System.out.println(multiples.get(j))
}
The var j holds the current value of your iteration, not the current index of the iteration.
This should be enough :
for (int j : multiples) {
System.out.println(multiples.toString());
total += j;
}
This is the given question:
Given a non-negative number represented as an array of digits,
add 1 to the number ( increment the number represented by the digits ).
The digits are stored such that the most significant digit is at the head of the list.
Example:
If the vector has [1, 2, 3]
the returned vector should be [1, 2, 4]
as 123 + 1 = 124.
This is my code:
public class Solution {
public ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int carry = 1;
int length = A.size();
ArrayList result = new ArrayList();
for( int i = length - 1; i >=0; i-- ){
int val = A.get(i) + carry;
result.add(0,val % 10);
carry = val / 10;
}
if (carry == 1){
result.add(0,1);
}
for (int j = 0; j < result.size(); j++){
if(result.get(j).equals(0))
result.remove(j);
else
break;
}
return result;
}
}
However, in the test case:
A : [ 0, 6, 0, 6, 4, 8, 8, 1 ]
it says my function returns
6 6 4 8 8 2
while the correct answer is
6 0 6 4 8 8 2
I have no idea what is wrong with my code.
Thanks!
if(result.get(j).equals(0))
result.remove(j);
else
break;
This will fail if every other index contains a 0. Here's what happens:
0 6 0 6 4 8 8 2
^ (j = 0)
The 0 will be removed, and j is incremented by one.
6 0 6 4 8 8 2
^ (j = 1)
Then this 0 is removed as well, skipping the first 6 in your array. To fix this, change the snippet to:
if(result.get(j).equals(0))
result.remove(j--);
else
break;
This compensates for when an index is removed so that j will not skip the number immediately after any removed 0s.
Check out a similar question at Looping through and arraylist and removing elements at specified index
simpler to do just
while (!result.isEmpty() && result.get(0).equals(0)) {
result.remove(0);
}
This will keep removing the left most 0 until there is no more left most zero to be deleted.
Your last for loop is removing 0 from your result ArrayList<Integer>. After removing that loop, you will get perfect output
public static ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int carry = 1;
int length = A.size();
ArrayList result = new ArrayList();
for (int i = length - 1; i >= 0; i--) {
int val = A.get(i) + carry; //2 8
result.add(0, val % 10); // 2 8
carry = val / 10;
}
if (carry == 1) {
result.add(0, 1);
}
// for (int j = 0; j < result.size(); j++) {
// if (result.get(j).equals(0))
// result.remove(j);
// else
// break;
// }
for (boolean isZero = true; isZero; ) {
isZero = result.get(0).equals(0);
if(isZero)
result.remove(0);
}
return result;
}