This question already has answers here:
Enhanced 'for' loop causes an ArrayIndexOutOfBoundsException
(2 answers)
Closed 5 years ago.
Created the below code whilst playing with loops. The code below stores the Fibonacci values into an array and then prints them using for loops.
int [] numbers;
numbers = new int[25];
numbers[0] = 1;
numbers[1] = 1;
System.out.println("Initializing the array values");
for(int i = 2; i < numbers.length; i++)
{
numbers[i] = numbers[i-1] + numbers[i-2];
}
System.out.println("Printing out Fibonacci values");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i] + ", ");
}
The above code works fine. The first time I threw it together though, I used an enhanced for loop to print out the values (the second for loop in the code). This compiles fine, but when I run it I get the following;
Initializing the array values
Printing out Fibonacci values
1, 1, 2, 3, 8, 34, 377, 17711, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 34
at ArrayDemo.main(ArrayDemo.java:21)
I don't get what went wrong. Changing the second loop shouldn't change the values (you'll notice the fibonacci values are wrong (ie missing values)). And I don't get why a simple enhanced for loop would skip indexes. Now, this isn't really a big deal because this isn't for a project or anything, it just bugs me that I can't figure out why it's doing it. Any clues?
The enhanced for loop just looked like this;
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
i here is the elements in the array, not the indexes. It could be bigger than numbers.length.
For example, if numbers = {1,2,3,9} then i will be 1, 2, 3, 9. But its length is 4, so when you loop on the elements inside it, you're trying to do numbers[9] which exceeds its size.
You probably want to System.out.print(i + ", ");
for(int i = 0; i <= numbers.length; i++) should be
for(int i = 0; i < numbers.length; i++)
In java, arrays are 0 based indexing. It means that your first element should be accessed at the index 0 and obviously the last at the length of your array minus 1.
int tab[] = new int[3]; //tab of length 3
tab[0] = 11;
tab[1] = 24;
tab[2] = 5;
Here you access the last element by calling tab[2] or tab[tab.length-1], which is equivalent.
Apologies, that was just a mistake in the code I put up in the
question.
The problem is that you should do : System.out.print(i + ", ");
You should read this and this about enhanced for loop.
The for statement also has another form designed for iteration through
Collections and arrays This form is sometimes referred to as the
enhanced for statement, and can be used to make your loops more
compact and easy to read. To demonstrate, consider the following
array, which holds the numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array.
So item holds the current value from the numbers array and not the current index. That's why you get an IOOBE.
for(int i : numbers)
{
System.out.print(numbers[i] + ", ");
}
should be
for(int i : numbers)
{
System.out.print(i + ", ");
}
You don't need to use indexes in enhanced for-loop.
Related
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.
I'm having a hard time using an array in a for loop that is supposed to cube numbers 1-9 in descending order. I keep getting an out of bounds error and the cubed values are completely off. I would greatly appreciate an explanation as to where I am going wrong with thinking about arrays. I believe the issue is with my index, but I'm struggling to explain why.
System.out.println("***** Step 1: Using a for loop, an array, and the Math Class to get the cubes from 9-1 *****");
System.out.println();
// Create array
int[] values = new int[11];
int[] moreValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Create variable to store cubed numbers
double cubedNumber = 0;
// Create for loop to count in descending order
for (int counter = 9; counter < moreValues.length; counter--)
{
cubedNumber = Math.pow(counter,3);
System.out.println(moreValues[counter] + " cubed is " + cubedNumber);
}
Output
Your main bug is the loop termination condition counter < moreValues.length, which if you're counting down will always be true.
Instead, check for the index being at or above zero:
for (int counter = 9; counter >= 0; counter--)
Your other bug is you're cubing the index, not the number pointed to by the index, so code this instead;
cubedNumber = Math.pow(moreValues[counter], 3);
To reduce confusion, you're better using an industry standard name for the loop variable, like i or where the loop variable is being used as an index to an array, index is often used and can improve code clarity.
Try:
for (int counter = moreValues.length; counter >= 1; counter--)
{
cubedNumber = Math.pow(counter,3);
System.out.println(moreValues[counter-1] + " cubed is " + cubedNumber);
}
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.
I am yet again stuck at the answer. This program prints the unique values but I am unable to get the sum of those unique values right. Any help is appreciated
public static void main(String args[]){
int sum = 0;
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for (int x : numbers) {
setUniqueNumbers.add(x);
}
for (Integer x : setUniqueNumbers) {
System.out.println(x);
for (int i=0; i<=x; i++){
sum += i;
}
}
System.out.println(sum);
}
This is a great example for making use of the Java 8 language additions:
int sum = Arrays.stream(numbers).distinct().collect(Collectors.summingInt(Integer::intValue));
This line would replace everything in your code starting at the Set declaration until the last line before the System.out.println.
There's no need for this loop
for (int i=0; i<=x; i++){
sum += i;
}
Because you're adding i rather than the actual integers in the set. What's happening here is that you're adding all the numbers from 0 to x to sum. So for 23, you're not increasing sum by 23, instead, you're adding 1+2+3+4+5+....+23 to sum. All you need to do is add x, so the above loop can be omitted and replaced with a simple line of adding x to sum,
sum += x;
This kind of error always occures if one pokes around in low level loops etc.
Best is, to get rid of low level code and use Java 8 APIs:
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sum = Arrays.stream(numbers)
.distinct()
.mapToInt(Integer::intValue)
.sum();
In this way there is barely any space for mistakes.
If you have an int array, the code is even shorter:
int[] intnumbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sumofints = Arrays.stream(intnumbers)
.distinct()
.sum();
So this is my first time commenting anywhere and I just really wanted to share my way of printing out only the unique values in an array without the need of any utilities.
//The following program seeks to process an array to remove all duplicate integers.
//The method prints the array before and after removing any duplicates
public class NoDups
{
//we use a void static void method as I wanted to print out the array without any duplicates. Doing it like this negates the need for any additional code after calling the method
static void printNoDups(int array[])
{ //Below prints out the array before any processing takes place
System.out.println("The array before any processing took place is: ");
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i != array.length - 1)
System.out.print(", ");
}
System.out.print("}");
System.out.println("");
//the if and if else statements below checks if the array contains more than 1 value as there can be no duplicates if this is the case
if (array.length==0)
System.out.println("That array has a length of 0.");
else if (array.length==1)
System.out.println("That array only has one value: " + array[0]);
else //This is where the fun begins
{
System.out.println("Processed Array is: ");
System.out.print( "{" + array[0]);//we print out the first value as it will always be printed (no duplicates has occured before it)
for (int i = 1; i < array.length; i++) //This parent for loop increments once the all the checks below are run
{
int check = 0;//this variable tracks the amount of times an value has appeared
for(int h = 0; h < i; h++) //This loop checks the current value for array[i] against all values before it
{
if (array[i] == array[h])
{
++check; //if any values match during this loop, the check value increments
}
}
if (check != 1) //only duplicates can result in a check value other than 1
{
System.out.print(", " + array[i]);
}
}
}
System.out.print("}"); //formatting
System.out.println("");
}
public static void main(String[] args)
{ //I really wanted to be able to request an input from the user but so that they could just copy and paste the whole array in as an input.
//I'm sure this can be done by splitting the input on "," or " " and then using a for loop to add them to the array but I dont want to spend too much time on this as there are still many tasks to get through!
//Will come back and revisit to add this if I remember.
int inpArray[] = {20,100,10,80,70,1,0,-1,2,10,15,300,7,6,2,18,19,21,9,0}; //This is just a test array
printNoDups(inpArray);
}
}
the bug is on the line
sum += i;
it should be
sum += x;
Given an array of integers ranging from 1 to 60, i'm attempting to find how many times the numbers 1-44 appear in the array. Here is my method
public static void mostPopular(int[] list, int count)
{
int[] numbers;
numbers = new int[44];
for (int i = 0; i<count;i++)
{
if (list[i]<45 )
{
numbers[i-1]=numbers[i-1]+1; //error here
}
}
for (int k=0; k<44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
I'm trying to iterate through the array, list, that contains over 5000 numbers that are between 1-60, then test if that number is less than 45 making it a number of interest to me, then if the integer is 7 for example it would increment numbers[6] By 1. list is the array of numbers and count is how many total numbers there are in the array. I keep getting an ArrayIndexOutOfBoundsException. How do I go about fixing this?
Replace this line numbers[i-1]=numbers[i-1]+1;
with numbers[list[i] - 1] = numbers[list[i] - 1] + 1;
Now it will update the count of correct element.
You need to increment numbers[list[i]] because that's your value which is smaller than 45. i goes up to 5000 and your array numbers is too small.
You should really start using a debugger. All the modern IDE have support for it (Eclipse, IntelliJ, Netbeans, etc.). With the debugger you would have realized the mistake very quickly.
If your initial value is less than 45, it will add 1 to numbers[i-1]. However, since you start with i=0, it will try to add 1 to the value located at numbers[-1], which doesn't exist by law of arrays. Change i to start at 1 and you should be okay.
Very close, but a few indexing errors, remember 0-1 = -1, which isn't an available index. Also, this isn't c, so you can call list.length to get the size of the list.
Try this (you can ignore the stuff outside of the mostPopular method):
class Tester{
public static void main(String args[]){
int[] list = new int[1000];
Random random = new Random();
for(int i=0; i<list.length; i++){
list[i] = random.nextInt(60) + 1;
}
mostPopular(list);
}
public static void mostPopular(int[] list)
{
int[] numbers = new int[44];
for (int i = 0; i< list.length ;i++)
{
int currentInt = list[i];
if(currentInt<45 )
{
numbers[currentInt - 1] = (numbers[currentInt -1] + 1);
}
}
for (int k=0; k<numbers.length; k++)
{
System.out.println("Number " + (k+1) + " occurs " + numbers[k]+ "times");
}
}
}
When i is 0, i-1 is -1 -- an invalid index. I think that you want the value from list to be index into numbers. Additionally, valid indices run from 0 through 43 for an array of length 44. Try an array of length 45, so you have valid indices 0 through 44.
numbers = new int[45];
and
if (list[i] < 45)
{
// Use the value of `list` as an index into `numbers`.
numbers[list[i]] = numbers[list[i]] + 1;
}
numbers[i-1]=numbers[i-1]+1; //error here
change to
numbers[list[i]-1] += 1;
as list[i]-1 because your number[0] store the frequency of 1 and so on.
we increase the corresponding array element with index equal to the list value minus 1
public static void mostPopular(int[] list, int count)
{
int[] numbers = new int[44];
for (int i = 0; i<count;i++)
{
//in case your list value has value less than 1
if ( (list[i]<45) && (list[i]>0) )
{
//resolve error
numbers[list[i]-1] += 1;
}
}
//k should start from 1 but not 0 because we don't have index of -1
//k < 44 change to k <= 44 because now our index is 0 to 43 with [k-1]
for (int k=1; k <= 44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}