For Loop in Array (Java) Index Out of Bounds - java

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);
}

Related

Find what number it used to be before element reset

Given an array with any size, in my case the array size is 5.
This array contains ALL numbers from 1 to 5 (must contain all of them)
[1 | 2 | 3 | 4 | 5]
0 1 2 3 4
And now, one element was reset and was set to 0, and the mission is to find what number it used to be before it turned 0.
So I have this simple solution:
Explained: First, loop from 1 to 5, create an inner loop to check if the i from the first loop exists in the whole array, if it doesn't exist, that means that it is the value it used to be before 0, because the array contained all numbers from 1 to 5 or 1 to 100 (doesn't matter) and there's on'y one rested element.
Code:
int[] numbers = new int[]{1, 2, 3, 4, 5};
numbers[1] = 0;
int lost = -1;
loop:
for (int i = 1; i <= numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
if (numbers[j] == i) {
continue loop;
}
}
lost = i;
break loop;
}
System.out.println(lost);
That solution is not bad, but I think there's a better solution, something more stable.
I have thought about it mathematically, in our example:
1 + x + 3 + 4 + 5 = 15
x = 2
Mathematically, it's really easy. Is there a way this can be done in a programming language as easy as it is mathematically?
Any better algorithms you can think of to solve this question?
This works for ONE element being reset. Just subtract each remaining element from the sum and what ever is left over would have been the previous number the element was before it was reset.
public static void main(String[] args) throws Exception {
int sum = 15;
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
numbers[4] = 0;
for (int i = 0; i < numbers.length; i++) {
sum -= numbers[i];
}
System.out.println(sum);
}
Results:
5
There is one more possibility, you can use HashMaps!
you don't have to traverse through any "for loops" then.
You can use Hashmaps to check whether is there any value for the key of "0", if yes then that is the case where some number is reset to 0.
Then you can traverse the Hashmap and compare which value is missing.
Everything is done With O(1) complexity and worst case of O(n) complexity.

how to add elements in a 2d array

I just want to know how this program works, and why the answer is 14.
here is the code:
public class extra {
public static void main(String[] args){
int[][] table = {{1,2,3},{4,5,6},{7,8,9}};
int sum = 0;
for( int i = 2; i > 0; i-- )
sum += table[i][3-i];
System.out.println(sum);
}
}
I understand the way the matrix is set up
123
456
789
but what is i in this problem, because I thought it was the number of rows, but since it is in a for loop, does it mean that i is the number in the matrix? Also how do the [i][3-i] come in to affect? The answer is 14, and I just want to know how it is 14.
It is only summing part of a diagonal, specifically table[2][1] which is 8, and table[1][2] which is 6.
The easiest way to see what is going on is to add an output statement in the loop:
for (int i = 2; i > 0; i--) {
sum += table[i][3 - i];
System.out.println(i + " " + (3 - i) + " " + table[i][3 - i]);
}
your program takes table[2][1] (value of 8) and table[1][2] (value of 6) elements, sums them and prints as output (value of 14)
regarding your question in a title your main method should be more like this:
public static void main(String[] args) {
int[][] table = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int sum = 0;
System.out.println("Before\n");
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
sum += table[i][j];
System.out.printf("Sum after %d iteration: %d\n", i + j + 1, sum);
}
}
System.out.println("\nIn total: " + sum);
}
i + j + 1 is a sum of current iteration which is sum of both axises, and since Java has 0-based indexed tables, it is increased by 1
Hope it helps!
i, in itself, does not correspond directly to anything in the matrix. It is just the name of the variable that the for loop changes each time it loops.
The [i][3-i] is how the i interacts with table. On the first round of the for loop, the i will be equal to 2. Thus, sum will be increased by table[2][1], which is the 3rd row and the 2nd column of the matrix, which has a value of 8.
On the second round of the for loop, the for loop, the i will be equal to 1. Thus, sum will be increased by table[1][2], which is the 2nd row and the 3rd column of the matrix, which has a value of 6.
Therefore, sum will be equal to 8+6=14.
What the for loop does is as follows:
i = 2. Enter loop.
Add table[2][3-2] to sum. Sum is now 8, because table[2][1] = 8.
Decrement i by 1.
i = 1. Enter loop.
Add table[1][3-1] to sum. Sum is now 14, because table[1][2] = 6.
Decrement i by 1.
i = 0. 0 is not greater than 0, so we exit the loop. The sum became 14.
Two-dimensional arrays like int[][] table have two indexes. One for the "outer" array (or rows), and one for the "inner" ones (columns).
Let's use int[][] table = {{1,2,3},{4,5,6},{7,8,9}}; from your code as an example:
table[1][2]: 1 means we should look in the array at index 1, which is {4,5,6}. 2 means we should look at {4,5,6}'s index 2, which is 6. In other words table[1][2] == 6.
table[2][0]: 2 means we should look in the array at index 2, which is {7,8,9}. 0 means we should look at {7,8,9}'s index 0, which is 7.
for (int i = 2; i > 0; i--)
so starting at 2 it checks if i is greater than zero
loops once then i-- subtracts 1
check again still greater than 0
loops again then subtracts 1 again
checks if greater than 0 now 0 it is not greater than 0 so stops looping
//thus loops 2 times
//[0] = 1st [1] = 2nd [2] = third ...
//counting in code starts at zero not 1 so and array of 3 counts a the spaces 0,1,2
int sum = 0;//sum starts at zero
//using the value of i translates as such
sum += table[2][3-2];//[2][1]this is 3rd group 2nd part so sum += 8
//then
sum += table[1][3-1];//[1][2]this is 2nd group 3rd part so sum += 6
0 + 8 + 6 = 14
Here's how to add elements in a 2D array in a easy way.
First when you initialize a 2D array think of the first brackets [ ] as a column and the second bracket [ ] as column rows.
For example: int[][] num = new int[10][5] which means 10 columns and 5 rows.
If you want to fill all the elements in a 2D array you must use two for loops:
int[][] num = new int[10][5];
for (int i =0; i < num.length;i++ ) {
for (int x=0; x < num[0].length;i++) { //we used num[0] because we need the length of the rows not the columns
num[i][x] = //any value you want to assign
}
}

How to find the smallest distance between two numbers next to each others in an array?

I have a sorted array. Let's say it is int [] numArr=new int[]{6, 9, 10, 27};
The smallest distance is between the 9 and the 10, and it is 1. The program should print this 1.
I am not expecting code, but I hope someone can give me an idea of how to proceed.
Declare a variable to hold the current minimum distance. It can be initialized to a really large number Integer.MAX_VALUE so that the first distance calculated becomes the initial minimum distance.
Use a for loop to loop over the values. You'll be accessing the element at the current index and the next index, so stop your for loop early to prevent an ArrayIndexOutOfBoundsException.
In the for loop, calculate the difference. If the difference is less than the current minimum, then update the current minimum to the current difference.
public static final int findSmallestDistance(final int[] pArray) {
int lMinimumDistance = Integer.MAX_VALUE;
for(int i = 1; i < pArray.length; i++) {
int lDifference = pArray[i] - pArray[i - 1];
if(lDifference < lMinimumDistance) {
lMinimumDistance = lDifference;
}
}
return lMinimumDistance;
}
Step 1: create a variable to save the actual smallest distance
Step 2: iterate through your array
Step 3: compare your actual number with the previous on your array (if this is the first element jump this step) and if it's smaller than your smallest save the result
Step 4: if the array has more elements, get the next one, else print your result
Here's some pseudocode:
Be smallest = a number surely greater than the one you're looking for
For each element i in array except the first
Be n = array[i] - array[i-1]
If n < smallest then
smallest = n
End If
End For
int numArr[] = {6, 9, 10, 27};
for(int i=0;i<numArr.length-1;i++){
if(numArr[i+1]-numArr[i]>0){
System.out.println("distance between " +numArr[i]+ " and "+numArr[i+1]+ " is: "+ (numArr[i+1]-numArr[i]));
}
}
int smallest = 100000
for (int i = 0; i < array.length; i++)
if(array[i+1]-array[i]<smallest)
{
smallest = array[i+1]-array[i];
}
System.out.println(smallest);

why does the index increases before looping

I cannot figure out why the for loop counter increases before I want it too / before it executes the entire for-loop block. I have littered the code with print statements for debugging, here is the code:
public void findSubSeq() {
temp = new ArrayList<Integer>();
temp.add(vals.get(0));
for (int i = 0; i < (vals.size()-2); i++) {
System.out.println(i + " index in array, for");
if (vals.get(i) < vals.get(i++)) {
System.out.println(i + " index in array, if 1");
temp.add(vals.get(i++));
System.out.println(i + " index in array, if 2");
System.out.println(this.getlargest());
}
else {
System.out.println(i + " index in array, else 1");
compareALs();
System.out.println(i + " index in array, else 2");
temp.add(vals.get(i++));
System.out.println(i + " index in array, else 3");
System.out.println(this.getlargest());
}
}
}
In the run of the code we can see that the counter i increases before the end of the for-loop. I am really confused. I have also tried a for-each loop with similar results.
Here is the run:
before subarrayB creation
before fillAL
Input file: inp
[1, 2, 3, 0, 4, 5]
before findSubSeq
0 index in array, for
1 index in array, else 1
1 index in array, else 2
2 index in array, else 3
[1]
3 index in array, for
4 index in array, else 1
4 index in array, else 2
5 index in array, else 3
[1]
You have vals.get(i++) which increments i. When used this way, ++ is a postincrement operator.
You really need to avoid using i++ inside the loop. That is what is causing your index variable to get incremented when you don't expect it. For example, your code does this:
if (vals.get(i) < vals.get(i++))
I think you really want to do this:
if (vals.get(i) < vals.get(i+1))
Similarly, when you add to temp, you really don't want to do i++, you want:
temp.add(vals.get(i+1));
if (vals.get(i) < vals.get(i++))
statement is like x < x, because increment accrues after get calling.
Use
if (vals.get(i) < vals.get(++i))
If you want to compare i-th and i+1 th elements.
The second: you have 3 increments of i in one cycle in one case by i. One in for cycle, the second in if and the 3-d, in add. Is it that which you planned?

Enhanced For Loop Exception [duplicate]

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.

Categories

Resources