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

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

Related

I was trying to solve a Leetcode problem, regarding identifying if the number entered is a palindrome or not

I understood the logic behind the problem's solution, but in the coded solution I am a bit confused about the return statement in the end. Please explain to me what is its significance, why is it being used, etc ? (not why return is used but why is that value being returned).
class Solution {
public boolean isPalindrome(int x) {
// 2 cases x < 0 = false case
// x > 0 = test case
if (x < 0 || x % 10 == 0 && x != 0){
return false;
}
else {
int newNum = 0;
while (x > newNum){
int r = (x % 10);
newNum = newNum * 10 + r;
x /= 10;
}
//the part I am confused about - below
return x == newNum || x == newNum / 10;
}
}
}
So to understand the Logic for the return statement let us take 2 numbers
1234321
678876
So one thing here While loop is doing is to create a new number(newNum) out of X and making sure that newNum stores the reverse of X till the middle point.
So in case of 1234321 , this while loop will execute till X=123 and newNum=1234.
After exiting out from while loop with these values, out of the 2 statements in return, x == newNum / 10 will give true result hence return statement will return true.which means the number is palindrome.
Please note here that the no. digits in given integer is odd(7)
Let us now Take other example 678876
In this case when the while loop ends, the value for the X would be 678 and newNum would be 678
out of the 2 statements in return, x == newNum this time will give true result hence return statement will return true again .which means the number is palindrome.
Please note here that the no. digits in given integer is even(6)
All in all, this statement return x == newNum || x == newNum / 10;
is to make sure that we are covering the condition for both Odd and even no. of digits in the given integer X.

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

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

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