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?
Related
goodday i am having an issue with my code. i am trying to iterate over an arraylist and see for which indices the values are increasing.
lines = [5, 7, 10, 11, 8, 6, 5, 4, 7, 8]
for (int i = 0; i < lines.size(); i++) { //iterate over array
// System.out.println(lines.get(i) + " ");
if (i == 9){
break;
}else if (lines.get(i) < lines.get(i + 1)){
System.out.println((i) + "-" + (i+1));
}else {
continue;
}
}
and my output produces this:
0-1
1-2
2-3
7-8
8-9
however i want my output to look like this:
0-3
7-9
You print directly after the if presence.
You would have to add another query after the first if. Something like this should solve the problem
`for (int i = 0; i < lines.size(); i++) { //iterate over array
// System.out.println(lines.get(i) + " ");
if (i == 9){
break;
}else if (lines.get(i) < lines.get(i + 1)){
if(lines.get(i) > lines.get(i+1){
System.out.println((i) + "-" + (i+1));
}
}else {
continue;
}
}`
You are printing every line, so it is expected the output is moving unit by unit.
What you can do is create a boolean that is initially set to false. Then, it will be set to true if the condition lines.get(i) < lines.get(i + 1) is true, and store the index i.
It will then change to false again whenever the condition lines.get(i) < lines.get(i + 1) is not true. Store the index again and only then print.
Trivial solution:
private static void compare( int start, int end )
{
if( start != end )
{
System.out.println( start + " - " + end );
}
}
public static void main(String args[]) {
int[] lines = { 5, 7, 10, 11, 8, 6, 5, 4, 7, 8 };
int start = 0;
for( int i = 0; i < lines.length - 1; i++ )
{
if( lines[i] >= lines[i + 1] )
{
compare( start, i );
start = i + 1;
}
}
compare( start, lines.length - 1 );
}
This can very likely be further optimized.
The code in your question is not a minimal, reproducible example so I understand that lines is a List. However you are accessing it as if it were an array so in the code, below, I used an array of int rather than a list of Integer.
The best way to understand how the code works is to run it through a debugger. If you are using an IDE, like IntelliJ or Eclipse, then it has a debugger.
Alternatively do a walk through of the code and write down the values of the variables as they change. This is known as debugging by hand.
int[] lines = new int[]{5, 7, 10, 11, 8, 6, 5, 4, 7, 8};
int end = lines.length - 1;
int lower = 0;
int upper = 0;
for (int i = 0; i < end; i++) { // iterate over array
if (lines[i] < lines[i + 1]) {
if (lower == upper) {
lower = i;
}
upper = i + 1;
}
else {
if (upper > lower) {
System.out.println(lower + "-" + upper);
}
lower = upper = i;
}
}
if (upper > lower) {
System.out.println(lower + "-" + upper);
}
The limit of the for loop must be one less than the size of the array, otherwise the lines[i + 1], on the last iteration of the loop, will be greater than the index of the last element in lines and that will cause an exception to be thrown.
After the for loop terminates, you need to check the values of lower and upper to see whether the last elements of lines are increasing. Hence the if statement after the for loop.
When I run the above code I get the following output:
0-3
7-9
I understand that this is your desired output.
Although you are working in Java this is more of an algorithm question than something specific to the language.
You'll need to keep track of the beginning of an incline as an independent variable. This is initially null because you do not know if the ArrayList begins with an incline or decline (or steady?). Since you want to keep track of the indexes, you'll need to iterate via the index - which you're already doing.
You are iterating from 1. This makes sense as it allows you to compare the current with the previous. Remove the break on the index 9 - this will cripple your algorithm if the number of elements varies. You should not make assumptions that the data your instructor will test with will be the same as the sample provided. They will look for edge cases that break a naive algorithm.
On a given iteration there are four possible states
you were on an incline and it continues through index
you were on an incline but it ended at previous index
you were not on an incline but you incline from previous index to index
you were not on an incline and you are not incling from previous index to index
There are only two cases where you do something - when you either begin or end an incline. Note that the List may end on an incline so you need to check for that case after completing the iteration. This has the distinct odor of a class assignment so I'm not going to provide Java code but the follow pseudocode describes the general algorithm.
let beginning-of-incline be null
for each index starting with 1
let inclining = is there an incline from the previous element to this element
if inclining and beginning-of-incline is null
capture beginning-of-incline
else if not-inclining and beginning-of-incline is not null
record incline from beginning-of-incline to previous index
clear beginning-of-incline
end-if-else
end for-each-index
if beginning-of-incline is not null
record incline from beginning-of-incline to final index of ArrayList
endif
I am writing a small code for bubble sort using Java as below
package raja.programming.bubblesort;
public class Main {
public static void main(String[] args) {
// write your code here
//int[] intArray = {5, -10, 22, 43, 1, 17};
int[] intArray = { 20, 35, -15, 7, 55, 1, -22 };
for ( int unsortedArrayIndex = intArray.length -1 ; unsortedArrayIndex > 0 ; unsortedArrayIndex--){
for ( int index = 0 ; index < unsortedArrayIndex ; index++){
System.out.println("index " + intArray[index] + " index+1 : " + intArray[index+1] );
if ( intArray[index] > intArray[index+1]) {
swap(intArray, index, index+1);
}
}
}
for (int num: intArray) {
System.out.println(num);
}
}
public static void swap( int[] array, int i, int j) {
if ( i == j) {
return ;
}
System.out.println("swap index " + array[i] + " index+1 : " + array[j] );
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
In the line if ( intArray[index] > intArray[index+1]) { I am passing as index+1 then only my code working, if I pass i++ or ++i its not working.
What is the reason behind this behaviour, please help me understand?
Thank you.
When you use index + 1 your code compares the element at the position index and the one at the position index +1 and the loop adds 1 at the end of the instuctions inside the loop
But if you use ++i or i++ your code will do the same thing but the index you used will jump by 2 the incrementation of the for loop and the incrementation you did.
it will not work if you do i++ beacuse this will increment i and return the previous value of i before incrementing so it's like you compare the element to itself
But if you use ++i it will increment the value of i and return the value incremented. But in both ways, in one loop, you increment i twice. If you really want to use either of those you need to remove the for loop and use a while loop and use ++i
i think the reason is. if u are using an index i for example and u increment it inside the loop, u will jump the next iteration. i++ is equals to i = i+1, but i+1 is not equals to i=i+1
You are iterating using index, when you are referring the position in an array using index + 1then the value ofindex` variable is not changed.
But if you use index++ or ++index, then you are incrementing the value of the index variable by 1 in that iteration and you will be skipping one index. Because of the same reason, the output array you are getting is unsorted in this case.
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 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
}
}
I am trying to use a for loop to create 7 instances of a class. I can go through the loop 7 times, but once I press enter I get an ArrayIndexOutOfBound error.
My code is as follows:
Data[] temperatures = new Data[7];
for(int i=1; i<=temperatures.length + 1; i++)
{
System.out.println("Please enter the temperature for day " + i);
temperatures[i] = new Data(input.nextDouble());
}
Array indexes start at 0. Therefore you must loop this way
for(int i=0; i < temperatures.length; i++)
That is because array index starts with 0, and it must not be greater than the array size.
In your case it starts from 1 to 8 and you array size is 7.
for(int i=0; i<temperatures.length; i++)
{
System.out.println("Please enter the temperature for day " + (i+1));
temperatures[i] = new Data(input.nextDouble());
}
ArrayIndexOutOfBoundsException
public class ArrayIndexOutOfBoundsException
extends IndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
This line is causing the error.
for(int i=1; i<=temperatures.length + 1; i++)
Your i in the loop should start from 0 as arrays in Java start from the 0th index.. Also your loop should go till i
This will navigate smoothly for 7 times.
Try this
for(int i=0; i < temperatures.length; i++)
Array indexes start at 0. The problem with your code is that you are trying to access the 8th array element which doesn't exist. For more information, refer The Java™ Tutorials - Arrays.
Your code should look something like this:
Data[] temperatures = new Data[7]; // Indexes 0-6 (makes a total of 7 indexes)
// Start the loop from index 0, end it to index 6 (= temperatures.lenght)
for (int i = 0; i < temperatures.length; i++) {
// Since it would sound strange to enter a temperature for day 0, notice (i+1)
System.out.println("Please enter the temperature for day " + (i+1));
temperatures[i] = new Data(input.nextDouble());
}
Arrays have index starting from 0 . IN your case indices would be 0 to 6
Solution :
1. Change Loop to for(int i=0; i