Class ArrayIndexOutOfBoundsException - trying to get rid of it - java

I am writing a program that will take user input for a random number and number of iterations. I am attempting to do a bubble sort on this (for my class I am required to do it with bubble and selection sorts). My initial code did fine till I worked to add in the portion to do iterations and then the selection sort. Now when I run my code, it will stop and give an error noted in the title of my post. The line it stops at is if randomArray[d]>randomArray[d+1] (the last line in the code below).
From what I have researched in my attempts to resolve this, it says the error is usually thrown when the array has been accessed by illegal index... or the index is negative or greater than the size of the array. I have attempted a few different things to fix this, but at the moment I am at a wall. If anyone can provide some direction, I would greatly appreciate it!
Thanks
Scanner input = new Scanner (System.in);
System.out.println("Enter a number please: ");
int n = input.nextInt();
//Get user input for number if iterations
System.out.println("Enter a number of iterations please: ");
int numIfor = input.nextInt();
//create array of random numbers
int[] randomArray = new int[n];
Random bubbleRandom = new Random();
//fill in the array of random numbers
for(int i=0; i < n; i++) {
randomArray[i] = bubbleRandom.nextInt(100);
}
//Printing the array before the sort
System.out.println("The numbers before the Bubble Sort: ");
for(int i=0; i < n; i++) {
System.out.print(randomArray[i] + " ");
}
System.out.println();
//Printing the array out after the Bubble Sort
int bubble = 0;
int sort = 0;
long startTime = System.currentTimeMillis();
for (int c=0; c < (numIfor - 1); c++)
{
for (int d=0; d < numIfor - c -1; d++)
{
if (randomArray[d]>randomArray[d+1])
{
bubble = randomArray[d];
randomArray[d] = randomArray[d+1];
randomArray[d+1] = bubble;
sort++;
}
}
}
long endTime = System.currentTimeMillis();
long runningTime = endTime-startTime;
System.out.println("The total number of iterations is: " + numIfor);
System.out.println("The total count of numbers sorted is: " + sort);
System.out.println("The total time elapsed was: " + runningTime);
System.out.println("The numbers after the Bubble Sort: ");
for(int i=0; i < n; i++){
System.out.print(randomArray[i] + " ");
}
}
}

What is probably happening is that d+1 is becoming larger than the last position of the array. You can make sure it only goes up to the end of the array by changing the last for loop as such:
The problem here is that you are looping to numIfor, which is a completely independent value from the length of the array (n). This means that if the user enters a numIfor and n, such that numIfor > n, then your code is bound to throw the exception.
The solution to this is using the actual length of the array as the limiter value instead, as such:
for (int c=0; c < randomArray.length-1; c++)
{
for (int d=0; d < randomArray.length-c-1; d++)
{
if (randomArray[d]>randomArray[d+1])
This is assuming that you want d to go through all the values of the array. But the real takeaway here is that you should always try to loop to less than the length of the array (the -1 is there because you are checking for array[d+1]). This works best if you are trying to reach all the values in the array because it guarantees that you don't go out of bounds.

Related

How can I make the script that counts which number occurred most often and counts how many times do each of the 10 random numbers occur

To explain about the program that I am making, it is program that asks the user how many times he would like his coin to flip. In this program, the coin of the head is even, and the odd is the tail.
I created a script that randomizes numbers from 1 to 10 based on the number you entered. And also I've made the script that how many odd and even numbers had come out, but I don't know how to make a script that shows how many times do each of the 10 random numbers occur and which number occurred most often.
Here is the script that I have made:
import java.util.*;
public class GreatCoinFlipping {
public static void main(String[] args) {
System.out.println("How many times do you want to flip the coin? : ");
Scanner sc = new Scanner(System.in);
int amount = sc.nextInt();
int[] arrNum = new int[amount];
int even = 0, odd = 0;
for (int i = 0; i < amount ; i++) {
arrNum[i] = (int)(Math.random() * 10 + 1);
System.out.println(arrNum[i]);
if (arrNum[i] % 2 == 0) even++;
else odd++;
}//end for
System.out.println("Head: " + even + ", Tail: " + odd);
}//end main
}//end class
What I am expecting on this script that that I want to make the script that shows how many times do each of the 10 random numbers occur and which number occurred most often and I want to make it by the count method. But the ramdon number part has to be in array method. Can someone please help me with this problem?
The arrNum variable will contain an array of all occurences of each number. So if you want to count, for example, how many times 4 occurred in this, you can do this:
Arrays.stream(arrNum).filter(n -> n == 4).count()
For 7 you can do this:
Arrays.stream(arrNum).filter(n -> n == 7).count()
And you can do the same for other digits (1 to 10).
This would be a simple/straight-forward way of doing it. You can also improve it by creating a method that returns this count:
public static int getCount(int[] arr, int num) {
return Arrays.stream(arr).filter(n -> n == num).count();
}
And then call this in a loop:
for(int i=1; i<=10; i++) {
System.out.println("Count for " + i + ": " + getCount(arrNum, i));
}
To keep track of the random number you generate you can use a array. The array starts out as all 0's and is of size 10 (because there are 10 numbers between 0-9).
int size = 10;
int numbers_counter[] = new int[size];
// initialize the values
for(int i = 0; i < size; i++){
numbers_counter[i] = 0;
}
// count some random numbers
for(int i = 0; i < 100; i++){
numbers_counter[(int)(Math.random() * size)] += 1;
}
// print how many times each number accured
for(int i = 0; i < size; i++){
System.out.println("" + i + " occured: " + numbers_counter[i] + " times");
}
You can apply this method to your code.

Bubble sorting issues in java

So I currently am having, this issue when I run my program it repeats the second display line. ("unsorted line")
I also am having trouble with the alignment when I run the program
What I need this program to do:
Generate 10 random integer numbers between 1 and 100, and place each random number in a different element of a single-dimension array starting with the first number generated.
Locate the largest of the 10 numbers and display its value.
Display the array's contents in the order the numbers are initially inserted. This is called an unsorted list.
Using the bubble sort, now sort the array from smallest integer to the largest. The bubble sort must be in its own method; it cannot be in the main method.
This is what I currently have programmed.. I just need help on adjustments when its ran.
import java.util.Arrays;
public class Chpt7_Project2 {
//Ashley Snyder
public static void main(String[] args) {
//create an array of 10 integers
int[] list = new int[10];
//initialize array of 10 random integers between 0 and 100
for (int i = 0; i < list.length; i++) {
list[i] = (int) (Math.random() * 100 + 1);
}
//Find the maximum of the list of random numbers generated
int maximum = -1;
int minimum = 999;
for (int i = 0; i < list.length; i++) {
if (maximum < list[i])
maximum = list[i];
if (minimum > list[i])
minimum = list[i];
}
//Display the maximum from the randTen array
System.out.println("The largest value is: " + maximum);
//Display the unsorted list of numbers from the randTen array
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + "The unsorted list is: ");
}
//Display the sorted array numbers
bubbleSort(list);
System.out.println("The sorted list is: " + Arrays.toString(list) + " ");
}
public static void bubbleSort(int[] list) {
//Sort randomly generated integers in randArray from lowest to highest
int temp;
for (int i = list.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (list[j] > list[j + 1]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
You're really close to making this work. Please notice that System.out.print("The unsorted list is: " + list[i]); is inside a loop. That means that "The unsorted list is" will print 10 times. You probably want to move the label part of the output before the loop while keeping the list[i] inside the loop. Then don't forget to put a System.out.println after the loop finishes. You will then see that each item is pushed together. To fix that just put list[i] + " " as part of the print.
It appears that your are a bit confused about two separate items. First is writing (printing) to the console. System.out.print("whatever"); and System.out.println("something");. The first one will write a line of text to the console but will not go to the next line. The second one writes and then goes (advances) to the next line.
Secondly, and really importantly is for. Whenever you see for (...) { whatever }; think that something (the whatever) is going to be repeated. The number of times that it will repeat is mostly / usually determined by the part in parenthesis. The thing that is repeated is between the braces {}.
I think this is what you want:
//Display the unsorted list of numbers from the randTen array
System.out.print("The unsorted list is: ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.println();
Please notice that the first System.out.print does not output to a new line, nor does the second one. The second System.output.print is repeated 10 times. Finally, System.out.println() starts a new line of output.

How to traverse through a one dimensional array in java [duplicate]

This question already has answers here:
Finding the minimum value of int numbers in an array (Java)
(10 answers)
Closed 5 years ago.
This is my first question on this site.
Anyways i'm making a program that will prompt the user for how many grades to enter. Then prompt the user to enter grades between 0 and 100 and store them in a array. Finally traverse the array to find the highest grade entered and display it to the user.
The problem i'm encountering is i have no clue on how to traverse through an array to compare two indexs in a array.
import java.util.*;
public class HighestGrade {
public static void main(String[] args) {
//Declare and Initialize Arrays and Scanner
Scanner scan = new Scanner(System.in);
int num = 0;
int[] array1;
int highestgrade = 0;
//Prompt user on how many grades they want to enter
System.out.print("How many grades do you want to enter: ");
num = scan.nextInt();
array1 = new int[num];
for(int i = 0; i < array1.length; i++){
System.out.print("Enter grade out of 100: ");
array1[i] = scan.nextInt();
}
//Traverse the array to find the highest grade entered
for (int i = 0; array1[0] < array1[i]; i++){
System.out.print("Higher");
}
//Display the results to the user
System.out.print("The highest grade is " + highestgrade + ".");
//Close scanner
scan.close();
}
}
To traverse through an array you can use a loop. For loop or while loop or do while loop.
To traverse through an array and keep track of the highest value you can maintain a variable and update it after each iteration if a value larger than that is encountered.
Speaking in terms of code..
int max = arr[0];
for ( int i = 0; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
System.out.println("Largest is : "+max);
Hope this helps..!!
Also you can use Recursion to traverse an array. But it is not recommended as it will lead to stack related issues..
Another approach to get the highest value without traversing can be seen like this..
Step 1 : Sort the array in ascending order
Step 2 : Highest value will be at the end of the array, Use it as highest value
In codes..
Arrays.sort(arr);
System.out.println("Highest Value is : "+arr[arr.length - 1]);
To traverse the array you need to change your for loop like this:
for (int i = 0; i < array1.length; i++){
// do something with array1[i]
}
Is actually what you already did to fill it. Just do the same to use its values. But there is an alternative to get the highest value, you can use Arrays.sort:
Arrays.sort(array1); // sort values in ascending order.
System.out.println(array1[array1.length-1]); // get the element in the last position (the greatest)

Modification of Bubblesort program with user input

I have created a program previously using the BubbleSort method that works to sort numbers in a list that already exists, however, I am having difficulty with trying to manipulate this program in order to allow a user to input the list of numbers to be sorted instead. So far I have:
import java.util.Scanner;
public class MedianValue {
public static void main(String[] args) {
//use scanner to input list of numbers to sort
Scanner scan = new Scanner(System.in);
int[] numbers = new int[] {scan.nextInt()};
//nested for loop
//outer loop just iterating
//inner loop going through and flipping
//checking if out of order (if statement)
int counter = 0;
//outer loop: keep doing this until it's sorted
for(int i = 0; i < numbers.length - 1; i = i + 1)
//put in a inner loop number.length times minus one because we don't want to swap the last element
for(counter = 0; counter < numbers.length - 1; counter = counter + 1)
{
if (numbers [counter] > numbers [counter + 1])
{
int temporary = numbers [counter];
numbers [counter] = numbers [counter + 1];
numbers [counter + 1] = temporary;
}
}
for(int i =0; i < numbers.length; i = i + 1)
{
System.out.print(numbers[i] + " ");
}
}
}
But, in this program, instead of sorting the inputted numbers, the program simply prints the first number that is inputted by the user. I am not sure if I need to move where my scanner function is placed, or add on to it within the loop for it to sort all of the numbers as I want it to do. I am lost on where to change the program if that is the case.
That's because int[] numbers = new int[] {scan.nextInt()}; is a single assigment. scan read a single input and assign to number[0].
You actually need to modify your code for scan to read n numbers and store in n-sized numbers.
something like.
int[] numbers = new int[scan.nextInt()];
for( int i = 0; i < numbers.length; i++)
numbers[i] = scan.nextInt();
The code int[] numbers = new int[] {scan.nextInt()}; will always create an array (not a List) of size 1.
Usually in these kinds of assignments you get n + 1 numbers, for example 5 3 6 2 4 1 would mean "I'm going to give you five numbers. Oh here they are: 3 6 2 4 and 1!"
You probably want something like int[] numbers = new int[scan.nextInt()]; - then loop from 0 to numbers.length to fill the array.

java array using scanner

In my program, I want to display an array using Scanner, i.e the user enters the array values during runtime.
public class NameComparator {
public static void main(String args[]) {
Scanner sn = new Scanner(System.in);
int n = sn.nextInt();
System.out.println("the array size is" + n);
int[] a = new int[7];
for (int i = 0; i >= a.length; i++) {
a[i] = sn.nextInt();
System.out.println("the value of a[i]" + a[i]);
}
sn.close();
System.out.println("array values are");
}
}
Here, I have got the array size from Scanner and then using for loop to get each array value, but I don't know why the array block hasn't executed. JVM just skips the for loop. Scanner works well
This:
for(int i=0;i>=a.length;i++)
should be:
for (int i = 0; i < a.length; i++)
You want to loop as long as i is smaller than a.length (i.e. the size of the array).
The for loop will be exited (or skipped) if the termination condition returns false. Since you're initializing i with 0, i>=a.length (i.e. 0 >= 7) will be instantly false.
Please note, that I've wrote i < a.length and not i <= a.length. The array size is currently set to 7, therefore the valid indices are from 0 to 6. You'll get an ArrayIndexOutOfBoundsException if you try to access index 7.
And you forgot to use your variable n to set the array size:
int[] a= new int[n];
There are few issues:
int[] a= new int[7];//<-- why hard coded?
int[] a= new int[n];// try, you already have array size from user
for(int i=0;i>=a.length;i++)//<-- condition fails, i is 0 for the first time
for(int i=0; i < a.length; i++)//try this
Take a close look at your for loop.
for(int i=0;i>=a.length;i++)
Notice that you are using a greater than sign.
Since i equals 0, the length of a would have to be 0 for this loop to run, and we already know that you declared a with a length of 7.
I would do some searching around because there's plenty of questions similar to this.
Regardless, you have a couple things incorrect. You prompt the user for an array size but then throw it out and use 7 instead:
int[] a= new int[7];
So, this should be:
int[] a= new int[n];
Second, your loop condition:
for(int i=0;i>=a.length;i++)
will be true as long as i is greater than a, which will never happen as long as a is a positive integer (because i starts at zero). So, if we're using less than, we should also remember that arrays are zero indexed, so if you input a value of 3, you only want to populate indexes 0, 1 and 2.
So, this should instead be:
for(int i=0;i < a.length;i++)
Finally, remember to prompt the user, even if this is just a learning exercise it's good practice. Put that all together and you'll get something like this:
public static void main(String args[])
{
Scanner sn=new Scanner(System.in);
System.out.println("Please enter an array size:" );
int n=sn.nextInt();
System.out.println("the array size is "+ n);
int[] a= new int[n];
System.out.println("Please enter your " + n + "array values:");
for(int i=0;i < a.length;i++)
{
a[i]= sn.nextInt();
System.out.println("The value of a[" + i + "] is " + a[i]);
}
sn.close();
System.out.println("Array values are " );
for (int arrayValue : a)
System.out.println(" " + arrayValue);
}
change the below code
for(int i=0;i>=a.length;i++) with for(int i=0;i<a.length;i++)
the condition should be < instead of >=
also use sn.hasNext() can simplify the solution.

Categories

Resources