How do I increase value of variable after second loop? - java

I am making a for loop for my robot. Basically, I want to robot to move one more row that the one before it after each loop. I want to start at how many rows the user wants eventually keep going. So if the user wants 4 row to begin with, it'll start off moving 4 rows, then it'll move for 5 rows, then it'll move for 6 rows, etc.
I used variable makeLine and put it as makeLine++ so it would increase each time by one. However, when I do this, it starts off at 5 instead of 4 each time.
How do I make sure it starts off at the value the user inputted but also go up by 1 after that?
Here's a part of my code:
public void makeShape(Robot rob, int rows) {
for(int count = 0; count < rows - 1; row++) {
turnLeft(rob, rows);
makeLine(rob, rows++);
turnRight(rob);
turnRight(rob);
makeLine(rob, rows += 2);

If it moves 5 you want to move 4 rows. I think You using loop by initializing by var=5, it means loop will occur 6 times, because loop is start counting from zero to 5, it means 6, for better help post code. so I can realize bugs in code.

Related

Is there a way to tell how many times a for loop will execute before running it?

I am taking an intro to java course and I am taking a practice quiz. These quizzes are not graded and do not count towards our grade so I thought I would post here.
Under normal circumstances, I would just copy the code and paste it into an IDE but I wanted to know if there is a way to think about this logically so I can figure out the answer. On real exams, we are not allowed to use eclipse or anything like that to figure out an answer and this question would take way too long to do it by hand and count how many times it goes through the for loop.
Here is the question:
How many times does the print statement in the for loop execute?
for(int i = 0; i <347589; i++) {
System.out.print("Give me coffee!");
}
You can basically just take the upper bound of the for loop as an answer, which is 347,589 in this case. To arrive at this answer, consider a for loop with a much smaller bound:
for (int i=0; i < 5; ++i) {
System.out.println("Give me coffee!");
}
By inspection, we can see that this loop will execute when:
i = 0
i = 1
i = 2
i = 3
i = 4
It won't execute when i = 5, because that fails the condition. So, it executes five times, which is the same as the upper bound of the for loop. We can extrapolate this to the loop in your problem to get 347,589 as the answer.
There is no general way to figure out how many times a while loop will execute before running it. This fact is known as the undecidability of the halting problem. For loops are just syntactic sugar for while loops, so this applies to for loops as well. The halting problem is the subject of a great many awesome books, among which Gödel, Escher and Bach by Douglas Hofstadter.
However, the for loop you give is extremely simple: it increases i until i no longer satisfies i < 347589. The variable i starts at 0 and increases one by one: i++ is equivalent to i = i + 1;. So i takes all the successive values: 0, 1, 2, 3, 4, ...,347588 and every time, the line System.out.println("Give me coffee!"); is executed.
Then i takes the value 347589 and no longer satisfies i < 347589, so the loop halts.
In total, "Give me coffee!" was printed 347589 times.
If you don't like the syntax for for loops, your code is equivalent to the following code using a while loop:
int i = 0;
while (i < 347589)
{
System.out.print("Give me coffee!");
i = i + 1;
}
As you have a simple for-loop that executes only one statement multiple times, you can simply count. You might know that the loop starts with i=0 with the first execution and adds 1 after each execution until the condition i<347589 is false. So:
i=0 -> once (1.)
i=1 -> twice (2.)
...
i=347588 -> 347589 times (347589.)
i=347589 -> loop stops.
so the print statement will be executed 347589 times.
In the course they might just want to check your knowledge towards the coding basics. In these type of problems you should notice most importantly 4-5 things.
1- Starting point of index.
2- Ending point of index, also check whether that value in included or not.
3- Increment/Decrement of index, whether index is increased/ decreased by 1 or some other value or pattern.
4- Is their any break statement inside the loop, which will also indicate that loop will run till specific condition.
In the example you gave starting point is 0 and end point is 347589 (excluded) with increment of 1, so loop will run. 347589 - 0 + 1( 0 based index) = 347589 times.
Obviously, FOR loop is not Java specific question.
To understand FOR loop properly let's take an easy example.
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
This code will print all number from 0 to 10 (Excluding).
So, the range 0-10 has 10 different values:
0
1
2
3
4
5
6
7
8
9
When i becomes 10 FOR loop statement (i<10) will not be satisfied and the loop will be broken.
So, in you case "Give me coffee!" will be printed 347589 times with the same logic.

Swapping a particular element with the one above it, in a randomly ordered ArrayList

I have a ArrayList from 1 - 9 that is randomly ordered and will be represented in three rows like this order for example:
6,5,7
4,8,1
9,2,3
It should be noted that I'm working with just a flat list, but I intend to represent it like above later on.
What I need is to be able to always swap the 9 element with the one above it. So for the configuration above I would need to swap the 9 and the 4. This needs to be done for any order where the 9 element might appear.
I've already created a switch statement that should do this when a user presses a key on the keyboard. So the logic of this swap should go in that switch case.
I wrote this code to try and achieve this goal, but it doesn't work as intended.
case 'u' :
int nineIndex = temp.indexOf(9);
int nine = 9;
int indexToSwapTo = temp.indexOf(9) - 3 % 9;
System.out.println("index of 9: " + nineIndex);
System.out.println("index to swap to : " + indexToSwapTo);
temp.remove(nineIndex);
temp.add(nineIndex, indexToSwapTo);
temp.remove(indexToSwapTo);
temp.add(indexToSwapTo, nine);
break;
The idea is, I first get the index of the 9 and then to get the index of the item above it I do the index at 9 - 3. I then perform some adds and removes. I should also note that the temp is an ArrayList that holds the random configuration of numbers. However this code doesn't work quite as intended. It does this instead:
The randomly order array list produces the following:
[6,1,8,3,7,**4**,2,5,**9**]
And after a swap occurs as described above, the ArrayList turns into this:
[6,1,8,3,7,**9**,2,5,**5**]
The printout says this as well which is useful:
index of 9: 8 index to swap to : 5. As you can see although it does swap the items in the correct place it for some reason puts index 5 as the item to be swapped rather than the actual value of index 5 which is 4. It also sometimes runs with out of bounds exceptions.
Use Collections.swap
You're way overthinking the problem. Just use the API available to you.
int nineIndex = temp.indexOf(9);
int indexToSwapTo = (nineIndex + 6) % 9;
Collections.swap(temp, nineIndex, indexToSwapTo);
Note this assumes that when 9 is on the top line, the "above" line is the bottom one, as in a circular way.
First off, the % operator in Java has a higher precedence than - so your line 4 is
equivalent to
int indexToSwapTo = temp.indexOf(9) - 3;.
This will work, but only for the last two rows. You should add some parentheses around the right hand side to cover every case, like this:
int indexToSwapTo = (temp.indexOf(9) - 3 ) % 9;
Secondly, there is a logical error in your code. In particular, in the first code block that adds and removes the ArrayList entries:
temp.remove(nineIndex);
temp.add(nineIndex, indexToSwapTo);
The second line is wrong, as it attempts to insert the index of the entry that you're meant to swap with, and not the value of that entry. In your example, the program correctly realises that it needs to swap the ArrayList entries at indices 5 and 8. However, in your code, you are telling the program to store 5 in the position of 9, instead of telling it to store the contents of index 5 in the position of 9 (which in this case, is the 8th entry of the ArrayList).
To fix your code, you should replace the code block above with this:
int value_to_be_swapped = temp.get(indexToSwapTo)
temp.remove(nineIndex);
temp.add(nineIndex, value_to_be_swapped);

Finding the desired sum in a row of a 2d array java

I'm having trouble wrapping my head around how to implement a method that starts with an int[][] input and a predefined sum value that returns an int[][] output that only displays the adjacent values in the row that add up to the sum. For example, if the input array was
int[][] input = new int[][]{
{3,4,4,2,7},
{2,3,2,8,6},
{1,4,2,1,2}
}
when the sum is set to 7, it would yield an output array with the following values
{3,4,0,0,7},
{2,3,2,0,0},
{1,4,2,1,0}
}
The output array should only display values that add up to a set number (7) with their neighbors, or if its a number from 0-9 values that are the desired sum (when you search for 7 it displays all 7s). To further clarify, as you can see in the output array, it displays the first two values, 3 and 4, because they add to 7. It displays 2,3,2 because they also add to 7. It prints out 1,4,2,1 on the bottom because 1,4,2 add to 7 and 4,2,1 add to 7. To summarize, it displays only values which are 7 or add up to 7 with the numbers next to them, and otherwise displays 0. Also the input values must be <0.
After brainstorming for a while I know that the code will need a number of nested loops: one to loop through the rows, inside that one to loop through the columns, inside that a loop to update the sum which stops when the sum equals the preset sum (7 in this case), and finally a loop to update the output[][]. However, I'm having a great deal of trouble on writing code that implements all of these loops correctly. I am planning on doing the same thing with numbers that add up vertically, but want to focus on horizontal as of now.
This can be done in O(NxM) complexity.
For each row, you keep two indexes (say, iLow and iHigh initialised to the first item input [i][0]) and a sumSoFar variable. At each iteration, if the sumSoFar < 7 you increment iHigh. If it is > 7 then you increment iLow and iHigh. If It is == 7 then you've found one combination + increment iLow and iHigh.
This should give the high-level idea of the algorithm and I'm sure that a lot of details are missing/incomplete but you should be able to put that in code.
You need three nested loops. Or really, three levels of nested loops with two loops after each other on the innermost level, but I will return to that in the end.
Before any loops, create the backbone of your result array. It’s OK if it’s an array of null references to arrays at this point.
Outer loop: loop through the outer array. A classical for loop is one option. For each entry, create an inner array of the correct length in the result, filled with zeroes for a start.
Middle loop, loop through the entries in the inner array. Again a classical for loop is fine. Your goal is that each iteration will determine if a series of adjacent values with the sum 7 begins at this entry, and if so, find out how long it is, and copy the entries in question to the result array.
Inner loop (first inner loop, that is) is for adding adjacent entries to find out if the sum is 7. You start from the entry from the middle loop and add up the values. This loop has a double stop condition: you stop when the sum is 7 or greater (assuming all values are positive), but obviously you also stop when reaching the end of the inner array. A while loop would be for my taste. Only if the sum hits exactly 7, do you use a new inner loop to copy the values to the result.
PS If you assume all values are positive, you shouldn’t just assume, you should check. In the middle loop, if the value in that entry is 0 or negative, throw an IllegalArgumentException.

Complex Loop with limited iterations and IF statement

The loop needs to scan an external file, from the bottom to the top. BUT...
When the loop has scanned 6 items from the external file, it needs to stop.
Then, IF there are less than 6 items to scan from the list on the external file it needs to print all of the those items to the screen.
I know how to do a loop that can scan the file from top to bottom using inFile.hasNext(); etc. I just don't know how to do from bottom to top and then define how many iterations I want the loop to actually do, with an if statement that is something like:
if (number of iterations < 6 print all)
{
JOptionPane.showMessageDialog(iteration1, iteration2, etc...)
}`
else if (number of iterations >= 6 only show the first 6 the loop has scanned)
{
JOptionPane.showMessageDialog(iteration1, iteration2, etc...)
}
Sorry about my awful pseudo code, just really stuck and this is the last part I need to do to finish my system!
any help would be brilliant!
I would recommend using a predefined class for reading backward. As to looping:
for(int i = 0; i < 6 && /* test for more input*/; i++)
{
JOptionPane.showMessageDialog( /*next input*/ );
}
I'd try instantiating an array with 6 empty strings and then concatenate the item you get in each iteration of the loop with the corresponding empty string in your array.
Afterwards you can check for your < 6 condition and depending on the result concatenate the string you want to give to your JOptionPane
You can't read a file from bottom to top. Instead, read the file (top to bottom) keeping the last (up to) 6 items read. When you hit the end if the file, test if you you have 6 items or not and act accordingly.
Use a LinkedList object, which allows removal of the element of the list via removeFist().
You could just store all items and use only the last 6, but that may mean using a lot of memory if the file is very large.

For Loop, Int Max

I am a beginner in Java, can somebody please explain me what this code means and how it comes to the answer of 15. I understand for loop but not what it is doing with int max.
int count;
int max = 3;
for (count = 1; count < 7; count++) {
max = max + 2;
}
System.out.println(max);
So for loops are counting loops. The can do something a certain number of times. In this case count starts at 1 and goes until 6 because last run that count is less than 7. So in effect the amount of max that starts at 3 and then has 2 added to it 6 times, the number of times the for loop runs. Hope this helps! I just finished my first year of CS, so Im glad I had a chance to help.
Max is initiated at 3. The code is adding 2 to max each time it goes through the for loop, a total 6 times (7 - 1). 3 + 2 + 2 + 2 + 2 + 2 + 2 = 15.
The for Loop:
A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number of
times.
A for loop is useful when you know how many times a task is to be
repeated.
From the definition, you want to do the addition which the task 6 times. In better sense, in your case, the relation ship between for loop and addition process is the for loop do the addition the 6 times.
For better understanding read following
Here is the flow of control in a for loop:
1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.
Note: read step 2 for your better understanding

Categories

Resources