Exception in thread java.lang.ArrayIndexOutOfBoundsException: 5 - java

I'm a newbie who is trying to complete the below tutorial
// Create a method called countEvens
// Return the number of even ints in the given array.
// Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
/*
* SAMPLE OUTPUT:
*
* 3
* 0
* 2
*
*/
Below is my code
public static void main(String[] args) {
int a[] = {2, 1, 2, 3, 4};
countEvens(a); // -> 3
int b[] = {2, 2, 0};
countEvens(b); // -> 3
int c[] = { 1, 3, 5};
countEvens(c); // -> 0
}
public static void countEvens(int[] x){
int i = 1;
int count = 0;
while ( i <= x.length){
if (x[i] % 2 == 0){
count ++;
}
i ++;
}
System.out.println(count);
}
The code can be run, but I get the below error message
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at apollo.exercises.ch05_conditionals.Ex5_CountEvens.countEvens(Ex5_CountEvens.java:23)
at apollo.exercises.ch05_conditionals.Ex5_CountEvens.main(Ex5_CountEvens.java:10)
May I know what I'm doing wrong here?

The line
while ( i <= x.length)
should be
while ( i < x.length)
If the length of xis 5, for example, the indices are 0, 1, 2, 3 and 4. The index goes from 0 up to one less than the length of the array.
However the tidiest way to do this is to use a for each loop rather than a while loop:
public static void countEvens(int[] x) {
int count = 0;
for (int number : x)
if (number % 2 == 0)
count++;
System.out.println(count);
}

'i' should go from 0 to length()-1, because array indices start at 0, and the index of the last element is length()-1.
Therefore, a correct version of your code would be:
public static void countEvens(int[] x){
int i = 0;
int count = 0;
while ( i < x.length){
if (x[i] % 2 == 0){
count ++;
}
i ++;
}
System.out.println(count);
}
For your specific purpose, a for loop would be simpler.
for(int i = 0; i< x.length(); i++){
if(x[i]%2==0){
count++;
}
}

At while ( i <= x.length), you're looping until i is equal to the length of x. The last index of an array is always length - 1, so change the less-than-or-equals (<=) to just less-than (<). Also, initialize i to 0, as Java arrays are zero-based.

Arrays in Java (and most other languages) are indexed starting at 0. However the length of an array is the count of the elements in the array. So for your array a[]
int a[] = {2,1,2,3,4};
The index goes up to 4, whereas the length is 5.
You are getting an index out of bounds error because you are iterating through the array from 1~5 because of the <= (less than equal to) operator, but the indices of the array are 0~4. When you access each element of the array you should use
if (x[i-1] % 2 == 0) //iterates from 0~4 rather than 1~5
otherwise you can set the iterator int i = 0; and use the less than < operator to ensure the iterator moves 0~4

Related

Filling rest of Array

I am writing a two's complement program where I convert decimal to binary using an array. I also want to have 8 Bits binary.
Since, for example, 22 is 10110 in binary, I want to fill the rest of the array with zeros, but I wasn't able to find a way how to do this.
Any help is appreciated.
Edit:
static void toBin(int number){
int[] bin = new int[8];
int i =0;
while (number > 0){
bin[i] = number % 2;
number = number/2;
i++;
}
// Here is where I would like to add zeros if the size of the array is below 0
for (int j = i-1; j>=0;j--){
System.out.println(bin[j]); //Array gets reserved
}
}
There is a class called "Arrays" that has a method called "fill()".
The syntax is "Arrays.fill()".
Inside the round brackets, after "fill", you have to put the value that will fill the rest of the array.
The example below fills the elements which have index from 0 to 5 (without 6) with the value 1.
int[] intArray = new int[8];
Arrays.fill(ints2, 0, 6, 1) ;
System.out.println(Arrays.toString(intArray));
Here is the output:
[1, 1, 1, 1, 1, 1, 0, 0]
Look at this code:
int number =22;
int bits[]= new int[8];
for(int i=0;i<=7;i++){
if(number>0){
bits[7-i]=number%2;
number/=2;
}
else{
bits[7-i]=0;
}
}
for(int i=0;i<=7;i++){
System.out.print(bits[i]);
}
I think, I have resolved your problem.
First initialize the whole string and reserve some space, like eight characters.
String binaryStr = "00000000";
for (int i = 0; i < binaryStr.Length (); i++)
{
if (binaryShouldBeOne)
{
binaryStr[i] = '1';
} else
{
binaryStr[i] = '0';
}
}
This may help.
int out[] = new int[8];
int in = 22;
int i = out.length - 1;
while (i >= 0 && in > 0) {
out[i] = in % 2;
in /= 2;
i--;
}
for (int j = 0; j < out.length; j++) {
System.out.print(out[j] + " ");
}
System.out.println("");
The array is initialized with zeros when it is created. You need just to change the required digits with 1 and rest will remain zeros. Try to start filling the array from 8th digit then decrement your counter so you may reach the most left digit.

Unsorted didgit in Insertion Sort Algorithm

// this describes the insertion sort algorithm
public class InsertionSort {
public static void main(String[] args) {
//array of unsorted integers
int [] array = { 10, 4, 1, 11, 5, 3, 8, 2, 0, 9};
int n = array.length;
for ( int j = 1; j<n; j++) {
//assign a value to the second element in the array
int key = array[j];
//assign a value to the 1st element in the list
int i = j-1;
//loop executes as long as i>0 and that the element befor the key is greater than the key itself
while( i>0 && array[i]>key) {
//move the bigger element 1 block forward
array[i+1] = array[i];
// keep moving until the element is in the right position
i =i-1;
}
array[i+1] = key;//assign the key to the appropritae location
}
for (int i=0; i<n; i++)
System.out.print(array[i] + " ");
System.out.println();
}
}
this is the ouput, As you can see, everything is sorted besides 10, which is still out of place in the array
10 0 1 2 3 4 5 8 9 11
This line has a problem:
while( i>0 && array[i]>key) {
The first iteration, j equals 1 and so i equals 0. And your loop doesn't run, because 0 is not greater than zero. But it should run, so the condition needs to change to "greater than or equals zero":
while( i>=0 && array[i]>key) {
That will fix your sort.

Trying to return an array with stored elements (java)

I am trying to store a set of numbers into an array with a for loop condition followed by if condition, and this method should return the array with stored elements respecting the conditional statement. I have been stuck in this problem for a while, but nothing is coming to my mind.
public int [] method ( int a) {
int [] newarray=new int[count];
for (int i=1; i<=a; i++) {
If (a%i==0) {
for (int m=0; m<count;m++) {
newarray[m]=a/i;
break;
}
}
}
return newarray;
}
public int [] method (int a) {
int [] newarray = new int[count];
for (int i = 1; i <= a; i++) {
if (a % i == 0) {
for (int m = 0; m < count; m++) {
if (newarray[m] == 0) {
newarray[m] = a/i;
break;
}
}
break;//Depending on your wanted solution
}
}
return newarray;
}
I've assumed that whenever an array-index contains a 0 it's uninitialized, and is considered empty.
In your original code, the second for-loop would overwrite the first index in the array every time. The if-statement I've added ensures that it only adds a number in an available slot.
I've also added a second break; Since you have two for-loops you need two breaks to completely get out of the loops. I didn't understand from your question whether or not this was something you wished for. Therefore, you have to decide whether or not to keep it in.
Edit:
Let's say this your array newarray when count == 10
0 0 0 0 0 0 0 0 0 0
This is what happens in you second for-loop:
for (int m = 0; m < count; m++) {
newarray[m] = a/i;
break;
}
First time in the loop is when m == 0 and so the lines that are executed are
newarray[0] = a/i;
break;
Then, because of the break; the program will exit the loop. What value a/i varies, but in this example, let's say a/i is 8. Therefore, newarray now looks like this:
8 0 0 0 0 0 0 0 0 0
Next time your program enters the second for-loop the exact same thing will happen. If a/i at that time is, let's say, 3, then we'll get
newarray[0] = 3;
break;
and your array will now look like this
3 0 0 0 0 0 0 0 0 0
As you can see, everytime your code runs, the first index will get overwritten. The if-statement I put in makes sure that it doesn't overwrite unless the array-slot equals 0(since that means it's empty).
With the extra if-statement
for (int m = 0; m < count; m++) {
if (newarray[m] == 0) {
newarray[m] = a/i;
break;
}
}
the first time around m == 0
newarray[0] is not equal to 0. (from last time: newarray[0] is 3)
therefore the code continues to m == 1
newarray[1] is equal to 0 and then
newarray[1] = a/i;
break;
is executed.
Hope that makes sense. Notice that there is a downside doing this. If a/i ever is 0, it will just get overwritten next time your loop runs.
From you code i presume you need and array containing count repeatition of elements of divisor of a variable. Eg if count is 5 and a is 10 you need an array like [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10]
If this is the case try
public int[] method(int a) {
List<Integer> list = new ArrayList<Integer>();
for (int i=1; i<=a; i++) {
if(a%i==0) {
int value = a/i;
for (int m=0; m<count; m++) {
list.add(value);
}
}
}
int[] newArray = new int[list.size()];
int index = 0;
for(Integer i : list){
newArray[index++] = i;
}
Arrays.sort(newArray);
return newArray;
}

Method taking in 2 arguments (array of ints, and a single int)

I've created a method, that, given a array of numbers and an integer n, it calculates the longest occurrence of the integer n. For example 1 0 0 0 1 1 1 1, given the number 1, the longest sequence is 4. I'm just using 0's and 1's at the moment to keep it simple, however I'm really stuck on implementing my main method to test this function - I'm not sure how to separate the integer "n" and the array of ints when reading from the command line, and I'm hoping I could be given some pointers/help. Here's my code:
public class OneB {
public static int longestSeq(int[] nums, int n) {
int max = 0;
int curLength = 0;
for (int i = 0; i < nums.length; i++) {
if (i == n) {
curLength++;
if (curLength > max)
max = curLength;
} else
curLength = 0;
}
return max;
}
public static void main(String[] args) {
int[] nums = new int[args.length-2];
int n = Integer.parseInt(args[args.length-1]);
for (int i = 0; args.length-1 > i; i++) {
nums[i] = Integer.parseInt(args[i]);
}
int result = longestSeq(nums, n);
System.out.println(result);
}
}
What I'm aiming is for the last number in the command line to be used as the integer n, whilst everything before that will be used as the array nums.
With the input 1 1 0 0 0 1 1 1 1 1 (the last 1 being my "n" value - 4 being the expected output") I get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at OneB.main(OneB.java:26)
Check the JavaDoc for ArrayOutOfBounds.
Then put a break point in your code (you already have the information needed to figure out which line) and step through your code slowly, watching the values of all your variables.

How can I locate and print the index of a max value in an array?

For my project, I need to make a program that takes 10 numbers as input and displays the mode of these numbers. The program should use two arrays and a method that takes array of numbers as parameter and returns max value in array.
Basically, what I've done so far is used a second array to keep track of how many times a number appears. Looking at the initial array, you will see that the mode is 4. (Number that appears most). In the second array, the index 4 will have a value of 2, and thus 2 will be the maximum value in the second array. I need to locate this max value in my second array, and print the index. My output should be '4'.
My program is good up until I attempt to produce the '4', and I've tried a few different things but can't seem to get it to work properly.
Thank you for your time!
public class arrayProject {
public static void main(String[] args) {
int[] arraytwo = {0, 1, 2, 3, 4, 4, 6, 7, 8, 9};
projecttwo(arraytwo);
}
public static void projecttwo(int[]array){
/*Program that takes 10 numbers as input and displays the mode of these numbers. Program should use parallel
arrays and a method that takes array of numbers as parameter and returns max value in array*/
int modetracker[] = new int[10];
int max = 0; int number = 0;
for (int i = 0; i < array.length; i++){
modetracker[array[i]] += 1; //Add one to each index of modetracker where the element of array[i] appears.
}
int index = 0;
for (int i = 1; i < modetracker.length; i++){
int newnumber = modetracker[i];
if ((newnumber > modetracker[i-1]) == true){
index = i;
}
} System.out.println(+index);
}
}
Your mistake is in comparing if ((newnumber > modetracker[i-1]). You should check if the newnumber is bigger then the already found max. That is if ((newnumber > modetracker[maxIndex])
You should change your last rows to:
int maxIndex = 0;
for (int i = 1; i < modetracker.length; i++) {
int newnumber = modetracker[i];
if ((newnumber > modetracker[maxIndex])) {
maxIndex = i;
}
}
System.out.println(maxIndex);
You could change last part to:
int maxIndex = 0;
for (int i = 0; i < modetracker.length; i++) {
if (modetracker[i] > max) {
max = modetracker[i];
maxIndex = i;
}
}
System.out.println(maxIndex);

Categories

Resources