Loop and if statement do not give desired output [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
public class Shuffle1 {
public static void main(String[] args) {
int x = 3;
if(x > 2) {
System.out.print("a");
}
while(x > 0) {
x = x - 1;
System.out.print("-");
}
if(x == 2) {
System.out.print("b c");
}
if(x == 1) {
System.out.print("d");
x = x - 1;
}
}
}
I'm learning Java from a book called "Head First Java", and I was using TextEdit as recommended in the book. I am supposed to be able to compile the code to get an answer of a-b c-d, but instead each time I compile it, I get a result of a---. I have checked it thoroughly myself and would really appreciate if anyone could help me.
Here is the original question from the book.

So if x is 3, I'll take you through what happens:
Print's out "a" because 3 > 2
Decrements x to 0, printing "--" on the way because it took 2 decrements to satisfy break condition, x > 0
That means it would correctly print a--. To achieve a-b c-d, you must the if statements inside the loop, like this:
while(x > 0) {
x = x - 1;
System.out.print("-");
if(x == 2) {
System.out.print("b c");
}
if(x == 1) {
System.out.print("d");
x = x - 1;
}
}
Now the execution cycle is:
x > 2, so print "a"
Goes into the loop
x becomes 2
Prints "-"
x is 2, so print "b c"
Continue iteration
Next iteration, x becomes 1
Print "-"
x is 1 so print "d"
x is now 0
Terminate loop
This gives the following desired result: a-b c-d.

This will print as per your expectation.
public class Shuffle1 {
public static void main(String[] args) {
int x = 3;
if(x > 2) { //First time x=3, which is true
System.out.print("a"); // print a
}
while(x > 0) { // x=3, which is true
x = x - 1; //first loop, x=2, then second loop x=1
System.out.print("-"); //prints "-"
if(x == 2) { // x=2, which is true
System.out.print("b c"); //prints "b c"
}
if(x == 1) { // as x=2, so it won't get display in first loop, but when it loop for second time, x become 1, which is true.
System.out.print("d");
x = x - 1;
}
}
}
}

Related

Why is "flag 5" of this code getting skipped? Why isnt the if statment running? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
so what I made here is a toString() method for 3d vectors. For example, if the ThreeDVector had components, x = 1, y = 1, z = 1. Then you run the toString() method, as shown in the main method at the bottom of this code. Then its supposed to print out, "i + j + k", but it only prints out "ijk", without the operaters. This is not the only problem, if you see how I added flag statements, after every if and else statement, some of them do not run at all. For example if you were to trace through the code, and you keep, "x = 1, y = 1, z = 1," in mind, then "Flag 5" is supposed to run?? The conditional statement before "Flag 5", states, "if(x != 0). That is true, because x = 1 in this scenario, and its supposed run that if statment and print out "Flag 5", but it just skips it?? I don't understand this much, I would be grateful if you could help out, thanks!
public class ThreeDVector
{
#Override
public String toString()
{
double x = this.x;
double y = this.y;
double z = this.getZ();
StringBuilder sb = new StringBuilder();
//x =1 , y = 1, z = 1
if (x != 0)//true
{
if (x != 1)//false
{
System.out.println("Flag 1");
sb.append(roundThreeDecimals(x) + "i");
}
else//true
{
System.out.println("Flag 2");
sb.append("i");
}
}
if (y != 0)//true
{
System.out.println("Flag 3");
if (y != 1 && y > 0)//false
{
System.out.println("Flag 4");
if (x != 0)//true (not working???)
{
System.out.println("Flag 5");
sb.append("+" + roundThreeDecimals(y) + "j");
}
else
{
System.out.println("Flag 6");
sb.append(roundThreeDecimals(y) + "j");
}
}
else if (y != 1 && y < 0)
{
System.out.println("Flag 7");
sb.append(roundThreeDecimals(y) + "j");
}
else
{
System.out.println("Flag 8");
sb.append("j");
}
}
if (z != 0)
{
System.out.println("Flag 9");
if (z != 1 && z > 0)
{
System.out.println("Flag 10");
if (y != 0 || x != 0)
{
System.out.println("Flag 11");
sb.append("+" + roundThreeDecimals(z) + "k");
}
else
{
System.out.println("Flag 12");
sb.append(roundThreeDecimals(z) + "k");
}
}
else if (z != 1 && z < 0)
{
System.out.println("Flag 13");
sb.append(roundThreeDecimals(z) + "k");
}
else
{
System.out.println("Flag 14");
sb.append("k");
}
}
return sb.toString();
}
//This main method will test the toString() method
public static void main(String[] args)
{
ThreeDVector d = new ThreeDVector(1,1,1);
System.out.println(d.toString());//this is supposed return i+j+k, but it only returns ijk
}
}
Why would 'flag 5' need to run? The if at flag4 doesn't, because y is 1, therefore y !=1 && y > 0 is false, thus the entire block, starting at print flag 3 and ending at the if (z != 0) line is skipped entirely. The expression isn't even evaluated - it's in a code block that isn't run at all.
Those flags indicate you're trying to debug this code, so you're doing what you're supposed to. I'm therefore not sure what to tell you for future endeavours; asking on SO every time you run into trouble doesn't seem like a sustainable practice. Perhaps take out pen and paper and follow through each if statement exactly, matching what you think should happen with what is actually happening (and those print statements should let you figure out what is actually going on). There where what you think doesn't match with what happens, you found a bug, and probably also where to look to fix this bug. Keep doing that, perhaps a bit more deliberately next time.

I need explanation why the output is a-b c-d [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
public class Main {
public static void main(String[] args) {
int x = 3;
while(x > 0) {
if(x > 2) {
System.out.print("a");
}
x = x - 1;
System.out.print("-");
if(x == 2) {
System.out.print("b c");
}
if(x == 1) {
System.out.print("d");
x = x - 1;
}
}
}
}
Output: a-b c-d
by the time "b c" is printed the value of x is supposed to be 2, why did "d" get printed as well?
look at the snippet closely
int x = 3;
while(x > 0) {
if(x > 2) {
System.out.print("a");
}
x = x - 1;
System.out.print("-");
if(x == 2) {
System.out.print("b c");
}
if(x == 1) {
System.out.print("d");
x = x - 1;
}
}
when loop runs for the first time the value of x is 3 and the following operations happens
while(x > 0) {
if(x > 2) {
System.out.print("a"); // as the value is 3 so it ll print
}
x = x - 1; // here value is 2 now
System.out.print("-"); // it ll be printed all the time the loop runs
if(x == 2) {
System.out.print("b c"); // again this ll be printed because the value is 2
}
if(x == 1) {
System.out.print("d");
x = x - 1;
}
}
now the value of x is 2 and the following operations happen
while(x > 0) { // value of x is 2
if(x > 2) {
System.out.print("a"); // it is skipped as the value of x is 2
}
x = x - 1; // now the value of x is 1
System.out.print("-"); // it gets printed again
if(x == 2) {
System.out.print("b c"); // it gets skipped as the value is 1
}
if(x == 1) {
System.out.print("d"); // it gets printed
x = x - 1; // loop gets over here as the value becomes 0
}
}
i have simplified it so that you understand well :)
Because the loop runs until X == 0, which means it will run once and print a, bc, Then it checks if X==0, which it isnt, x = x-1, now x == 1 and prints d. The loop runs once more, makes x == 0, and then it stops
First round - X == 3, so it prints "a",
X = X - 1, Now x == 2
X== 2, so it prints "bc"
jumps over the last if statement since x > 1.
Second round
X is not 3 so it doesnt print.
X = X -1, now x == 1,
X is not 2, so now print,
X== 1 so it prints d.
third round since X > 0
only thing happening is X = X -1;
now X == 0, and the while loop will end
The best is to go through the code like a debugger. Line after line.
You see you have your program wrapped in a while loop, while(x>0) means the whole block of the code will be repeated as long as x is bigger than 0.
While 1st iteration
You are right in first iteration after "b c" is printed out the value of x is 2. and program will skip printing "d". At this point the while loop 1st iteration is over.
While 2nd iteration
Now the condition of the while is checked x is 2, that means (x > 0) and program will enter the second iteration of the while loop. "a" will not be printed. x is getting decreased to 1. "b-c" will not be printed. As x is 1 "d" will be printed to console.
While 3rd iteration
Condition checks value of x. x=1, its bigger then zero so again while loop executes. This time x is decreased to 0. Nothing gets printed as none of the if statements is satisfied.
End
As x is 0, its not bigger than 0 anymore, condition of the while loop is not satisfied. While loop will not be executed and program will end.
Check and play with the while loop
Oracle docs
W3schools

Why does this loop infinitely execute if the condition for the for loop is above 2?

public class Proof {
public static void main(String[] args) {
for (int x = 1; x < 3; x++) {
do {
if (x == 0) {
x = x * 3 + 1;
} else if (x % 2 != 0) {
x = x * 3 + 1;
} else if (x % 2 == 0) {
x /= 2;
}
System.out.println(x);
} while (x != 1);
System.out.println("DONE!!!!!!");
System.out.println();
}
}
}
To test this issue just change x < 3 to 2 and it works fine. Then change it back to 3 and it doesn't work. I'm just a new programmer but I'm confused about this.
So, when x == 1, you go through the do while loop and eventually the value goes back to 1, you exit and then you iterate the for loop to 2... That would exit the for loop when you change is to x < 2.
When x < 3, what happens? X goes through the do while loop just like before, but you don't exit the for loop at 2, you actually go back into the do while loop. But when do you exit the do while loop??? Only when x == 1... so then what happens to your for loop? It iterates x to..... 2 again. And you are back in your do while loop. Forever!
As Casey said, the debugger will show you this and is incredibly useful. Good luck going forward!
Once your for loop reaches it's second iteration (x = 2), your do while loop will set it back to 1 (x /= 2), and your for loop increments it back to 2 (x++), causing the process to repeat infinitely.
Here's a visual:
x is initially equal to 1.
Go through the first else if condition, x is increased to 4.
x != 1 at this point; iterate in the while loop again, and go through the second else if condition. x is divided by 2 and is therefore equal to 2.
When equal to 2, x%2 ==0 is true, x is divided by 2 again and goes down to 1.
The while loop is exited as x is equal to 1.
Back to the for loop, x is increased to 2, and you go back through the second else if condition.
You're back to the fourth step, thus reaching a cycle in the calculation and having the infinite loop execution you described.

Java code not printing to console in Eclipse

I have this java code in eclipse. When I run it, I assume I should get something back in the console at the bottom of eclipse. This is not the case. The console at the bottom of eclipse is blank.
package com.veggiedogtreats.javacode;
public class doobeedoobeedo {
/**
* #param args
*/
public static void main(String[] args) {
int x = 1;
while (x < 0) {
System.out.println("Doo");
System.out.println("Bee");
x = x + 1;
}
if (x == 2 ) {
System.out.print("Do");
}
}
}
you have the while loop set to x < 0, it should be x > 0. The way you have it, it will never enter the while loop
Your while condition is wrong. it should read while ( x > 0 ) instead of while ( x < 0 )
Your program only prints to the console when x is less than zero and when x is 2.
x always has a value of 1.
int x = 1; // x is 1
while (x < 0) { // 1 is not less than zero, doesn't enter the loop
System.out.println("Doo");
System.out.println("Bee");
x = x + 1;
}
if (x == 2 ) { // 1 is not two, doesn't enter the if
System.out.print("Do");
}
Maybe you wanted something like this:
while (x < 0) { .... }
your conditions are not satisfied and hence the sysout statements are not executed. Either change the initial value of x or the conditions so that the sysout statements are executed atleast once.
Neither of the conditional statements are true. 1 is not less than zero or equal to 2.

How to end my recursion

I need to program a method to solve a maze (2-dimensional array). I need to stay directly left of the wall at all times and my method should end when either I've reached the exit point (which is always at the same position) or when there is no solution possible (and, after running through the maze I'm back at the entry point).
I was able to do all that, no problems, I can visually ensure that it's doing what I want it to do (we've got some other methods from our instructor which output the visuals) and my console debug output is right as well.
This is the relevant code:
public static void main(String[] args) {
maze = generateMaze(10,10);
walk(1,0,0);
}
public static void walk(int x, int y, int direction) {
System.out.println("x = " + x + " y = " + y); //debug output
draw(x,y,maze); //draws current position
if (x == maze.length-1 && y == maze[1].length-2) { //terminate when reached exit
System.out.println("Geschafft!");
return;
}
if (x == 1 && y == 0 && direction == 3) { //terminate when at starting point again (no solution)
System.out.println("Keine Lösung möglich.");
return;
}
if (direction == 0) { //go down
if (maze [x][y+1]) {
walk(x,y,1);
}
walk(x,y+1,2);
}
if (direction == 1) { //go right
if(maze [x+1][y]) {
walk(x,y,3);
}
walk(x+1,y,0);
}
if (direction == 2) { //go left
if(maze [x-1][y]) {
walk(x,y,0);
}
walk(x-1,y,3);
}
if (direction == 3) { //go up
if(maze[x][y-1]) {
walk(x,y,2);
}
walk(x,y-1,1);
}
}
There's just one problem: how do I end my recursion correctly? This is what I get form the console:
x = 1 y = 0
x = 1 y = 1
x = 1 y = 1
x = 1 y = 2
and so on...
x = 8 y = 8
x = 9 y = 8
Geschafft!
x = 8 y = 9
x = 8 y = 9
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at maze.MazeSolution.walk(MazeSolution.java:26)
at maze.MazeSolution.walk(MazeSolution.java:39)
and some more of that
I do understand the error, the recursion obviously doesn't end where I want it to and x or y are increased and try to use an index in the array that isn't there.
Why doesn't the recursion end with the return statement, when either of these situations come true:
if (x == maze.length-1 && y == maze[1].length-2) { //terminate when reached exit
System.out.println("Geschafft!");
return;
}
if (x == 1 && y == 0 && direction == 3) { //terminate when at starting point again (no solution)
System.out.println("Keine Lösung möglich.");
return;
}
What do I need to do to end it correctly?
I greatly appreciate your help, show some love for a beginner and tell me what to do.
Add to the beginning
public static void walk(int x, int y, int direction) {
System.out.println("x = " + x + " y = " + y); //debug output
if (x >= 10 || x < 0 || y >= 10 || y < 0) return;
Look at your returns and where you may return to. You can return in the middle of your enclosing function which has other calls to walk, without the guards to ensure they're not called.
I recommend re-implementing your logic; think about having if/else pairs to ensure mutual exclusion.
Why don't you simply return true or false and react on it?
So basically you add to your two end cases return true; for code ended.
if(walk(...)) return true;

Categories