im getting a out of bounds error on line 57. any help is appreciated. the program takes 1 integer and creates and array with that many indexes. it then asks for more integers to fill it up. it then takes all the even numbers and places it into a second array with is then outputted.
run:
Enter the ammount of integers you will require.
10
Enter your integers:
1
Enter your integers:
2
Enter your integers:
3
Enter your integers:
4
Enter your integers:
5
Enter your integers:
6
Enter your integers:
7
Enter your integers:
8
Enter your integers:
9
Enter your integers:
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at AllEven.arrcheck2(AllEven.java:57)
at AllEven.main(AllEven.java:24)
Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)
CODE
import java.util.*;
public class AllEven {
public static void main(String[] args) {
int read;
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the ammount of integers you will require.");
read = kybd.nextInt();
int[] arr1 = new int[read];
int[] arr2;
int count = 0;
arrRead(arr1);
arrcheck(arr1);
arr2 = new int[count];
arrcheck2(arr1, arr2);
mainPrint(arr2);
}
public static int arrcheck(int[] arr1) {
int count = 0;
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] % 2 == 0) {
count++;
}
}
return count;
}
public static void arrRead(int[] arr1) {
Scanner kybd = new Scanner(System.in);
for (int i = 0; i < arr1.length; i++) {
System.out.println("Enter your integers: ");
arr1[i] = kybd.nextInt();
}
}
public static void arrcheck2(int[] arr1, int[] arr2) {
int j = 0;
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] % 2 == 0) {
arr2[j] = arr1[i];
j++;
}
}
}
public static void mainPrint(int[] arr2) {
for (int i = 0; i < arr2.length; i++) {
System.out.println("Printing Even Numbers.");
System.out.println(arr2[i]);
}
}
}
ok so thanks everyone who helped, But now after the integers have been inputted the program just finishes without displaying anything after.
You need to assign the return value of arrcheck invocation in count variable before creating arr2. Otherwise, you would create your arr2 with size 0.
Change: -
int count = 0;
arrRead(arr1);
arrcheck(arr1);
to: -
arrRead(arr1);
int count = arrcheck(arr1);
After brief look at the code I think your problem lies here:
int count = 0;
arrRead(arr1);
arrcheck(arr1);
arr2 = new int[count]; //array of size 0!
arrcheck2(arr1, arr2);
You are defining arr2 as a zero-length array:
int count = 0;
....
arr2 = new int[count];
Then, in arrcheck2 you have the line:
arr2[j] = arr1[i];
This will not work because arr2 has no length so you cannot put anything into it.
The size of arr2 is 0. so when you try to access a non existing index in it you get the exception.
You create an array with length 0.
arr2 = new int[count];
You should give it a length bigger than 0.
If you want it to be the same length as arr1 just do arr2 = new int[read];
You need to initialize arr2 to the same length as arr1. int count = read will fix the issue. Or you can remove count entirely and just use read when initializing the array.
read = kybd.nextInt();
int[] arr1 = new int[read];
int[] arr2;
int count = read;
arrRead(arr1);
arrcheck(arr1);
arr2 = new int[count];
For starters you have your arrcheck function returning a count and not doing anything with it. I suspect you meant to write something like this:
arrRead(arr1);
int count = arrcheck(arr1);
otherwise your next line:
arr2 = new int[count];
creates an array of size 0 which will cause array out of bounds as soon as it is accessed.
Also you spelled Amount wrong, I think the rest of the program should work with the above change.
You are not initializing your array int[] arr2. You should not use an array to populate even elements from the initial array because arrays require a determined size upon initialization -- you are better off using ArrayList and then conver it into an array once you know the definitive size, if you must.
Related
I am learning operations on 1 dim array.
It has three parts:
Set the 10 elements of integer array counts to zero.
Add one to each of the 15 elements of integer array bonus.
Display the five values of integer array best Scores in column format.
I have already figured out the 3. I need help in figuring out 1 and 2.
This is my code:
public class OneDimArrayOperations {
public static void main(String [] args){
// a) Set the 10 elements of integer array counts to zero.
int [] zeroArray = new int[10];
for (int i = 10; i == 0; i--) {
System.out.println("Count to zero from 10 elements" + zeroArray);
}
// b) Add one to each of the 15 elements of integer array bonus.
int [] arrayBonus = new int[15];
for (int i = 0; i <arrayBonus.length; i++) {
System.out.println("Bonus array values "+ arrayBonus[i]);
}
//c) Display the five values of integer array bestScores in column format.
int [] bestScores = {100,95,85,45,65};
System.out.printf("%n%s%12s %n", "Value", "BestScores");
for (int counter = 0; counter < bestScores.length ; counter++) {
System.out.printf( "%d%9d%n" , counter , bestScores[counter]);
}
}
}
part a:display:10,9,8,7,....1,0
for(int i=10;i>=0;i--)
part b:i havent understood your question
The line int[] zeroArray = new int[10]; will create an int array of size 10 and initialise all elements to zero. That's the default behaviour in Java.
for(int i = 0; i < arrayBonus.length; i++) { arrayBonus[i]++; } will solve your second problem.
I am getting an error and I cant quite understand the cause. I'm trying to get user-input using the Scanner method to assign values to the indices of an array, numbers. The user is allowed to keep - continue - entering values into the array numbers, however, if the user decides to stop, entering 0 will break the assignment of array-index values.
int[] numbers = new int[100];
int[] countIndex = new int[100];
int[] numberOcc = new int[100];
for (int i = 0; i < countIndex.length; i++)
{
countIndex[i] = i;
}
System.out.println("Enter your integer values: ");
for (int i = 0; i < numbers.length; i++)
{
if(input.nextInt() == 0)
{
break;
}
else
{
numbers[i] = input.nextInt();
}
}
This piece of code is a small part of a much larger code, however, it is very important. The error I'm getting is that the code is allowing the user to enter twice before moving to the next index, but the first integer entered it always skipped:
Enter your integer values:
1
2
0
0 occurs 99 times
2 occurs 1 time
UPDATES
System.out.println("Enter your integer values: ");
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = input.nextInt();
if(numbers[i] == 0)
{
break;
}
}
Why is it that the 1 is ignored as input?
Also, is using input.nextInt() as the condition of an if-else statement bad code design?
From the comments
However, a 0 is still being placed in the index,
By default, int values will be assigned 0. So when you don't assign non zero values to int, they will still be 0.
One way around that is to use arraylist. Then once you enter all the numbers, you can convert arraylist to array.
Simple example without any input validation
List<Integer> list = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] defaultArray = new int[n];
// do validation for n
//assume n = 5 with values 1,2,0,3,2
for (int i = 0; i < n; i++) {
int temp = in.nextInt();
if (temp != 0) {
list.add(temp);
defaultArray[i] = temp;
}
}
Integer[] positiveArray = new Integer[list.size()];
positiveArray = list.toArray(positiveArray);
System.out.println(Arrays.toString(defaultArray)); //will print [1, 2, 0, 3, 2]
System.out.println(Arrays.toString(positiveArray)); //will print [1, 2, 3, 2]
If you want to convert Integer arraylist to int array, just search on google and there are many similar questions.
Demo
Whenever I am trying to run this code, it gives me out of bound exception. Can anyone point me out what's wrong with it.
package com.programs.interview;
import java.util.Scanner;
public class FindMaxNumInArray {
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter the size of the array: ");
int arraySize = scan.nextInt();
int[] myArray = new int[arraySize];
System.out.print("Enter the " + arraySize + " values of the array: ");
for (int i = 0; i < arraySize; i++)
myArray[i] = scan.nextInt();
for (int j = 0; j < arraySize; j++)
System.out.println(myArray[j]);
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
}
public static int maximum(int[] arr, int Arraylength){
int tmp;
if (Arraylength == 0)
return arr[Arraylength];
tmp = maximum(arr, Arraylength -1);
if (arr[Arraylength] > tmp)
return arr[Arraylength];
return tmp;
}
}
Output
Enter the size of the array: 5 Enter the 5 values of the array: 1 2 3
4 5 1 2 3 4 5 Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5 at
com.programs.interview.FindMaxNumInArray.maximum(FindMaxNumInArray.java:26)
at
com.programs.interview.FindMaxNumInArray.main(FindMaxNumInArray.java:17)
This is the problem:
if (arr[Arraylength] > tmp)
Valid array indexes go from 0 to length-1 inclusive. array[array.length] is always invalid, and on the initial call, ArrayLength is equal to arr.length.
It's not clear why you're using recursion at all, to be honest. An iterative solution would be much simpler - but you'll need to work out what you want to do if the array is empty.
EDIT: If you really want how I would write the recursive form, it would be something like this:
/** Returns the maximum value in the array. */
private static int maximum(int[] array) {
if (array.length == 0) {
// You need to decide what to do here... throw an exception,
// return some constant, whatever.
}
// Okay, so the length will definitely be at least 1...
return maximumRecursive(array, array.length);
}
/** Returns the maximum value in array in the range [0, upperBoundExclusive) */
private static int maximumRecursive(int[] array, int upperBoundExclusive) {
// We know that upperBoundExclusive cannot be lower than 1, due to the
// way that this is called. You could add a precondition if you really
// wanted.
if (upperBoundExclusive == 1) {
return array[0];
}
int earlierMax = maximumRecursive(array, upperBoundExclusive - 1);
int topValue = array[upperBoundExclusive - 1];
return Math.max(topValue, earlierMax);
// Or if you don't want to use Math.max
// return earlierMax > topValue ? earlierMax : topValue;
}
you can't access
arr[Arraylength]
the last element would be at
arr[Arraylength -1]
for example if you have
int arr[] = new int[5];
then the elements would be at 4, because index starts from 0
arr[0], arr[1], arr[2], arr[3], arr[4]
Your issue is in the following piece of code:
if (arr[Arraylength] > tmp)
return arr[Arraylength];
Indexes start at 0, so you will be out of bound for an array with 5 elements [1,2,3,4,5] indexes: [0,1,2,3,4].
I would use a plain loop. Java doesn't do recursion particularly well.
public static int maximum(int[] arr) {
int max = Integer.MIN_VALUE;
for(int i : arr) if (i > max) max = i;
return max;
}
here
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
you are passing the arraysize where in maximum method you are returning arr[Arraylength] which giving ArrayIndexOutOfBound so change either in calling maximum(yArray,arraySize-1) or return arr[Arraylength-1] statement.
I'm trying to create a method that takes in 3 int arrays and prints out one element from each array until all the elements of all three arrays have been printed at least once. The first array has 10 elements, the second has 7, and the third has 2. The elements are selected and printed at random. Any help would be appreciated. The idea is to see how many iterations it would take to print out all the elements at least once. I don't know the conditions to set for
a large scale iteration like this. My code so far (with just one array as a parameter):
import java.util.*;
public class calculateAverage{
private static int[] x = new int[]{1,2,3,4,5,6,7,8,9,10};
private static int[] y = new int[]{1,2,3,4,5,6,7};
private static int[] z = new int[]{1,2};
public static void main(String[] args){
calculate(x);
}
public static void calculate(int a[]){
Random random = new Random();
for(int i = 0;i < a.length; i++){
System.out.print(a[random.nextInt(a.length)] + " ");
}
System.out.println();
}
}
code output:
7 2 4 1 8 10 3 10 7 3
Solution for one array:
public static int calculate(int a[]){
Random random = new Random();
HashSet<Integer> remaining = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
remaining.add(i);
}
int i = 0;
while (!remaining.isEmpty()) {
int index = random.nextInt(a.length);
System.out.print(a[index] + " ");
remaining.remove(index);
i++;
}
System.out.println();
System.out.println("Finished after " + i + " iterations.");
return i;
}
You could use a collection like Set to keep track of indexes that were already picked. Each time you generate a random number you would first check if it already exist in the Set. If not, print the value in array and add the index number to the set.
Your loop would end when size of that set equals size of the array.
int a[] = {4, 6, 3, 2, 9, 1, 5};
Set<Integer> set = new TreeSet<Integer>();
int counter = 0;
Random rand = new Random();
while(set.size() != a.length){
set.add(a[rand.nextInt(a.length)]);
counter ++;
}
System.out.println("Total Iterations : "+counter);
return counter;
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);