If-Else Control Flow without curly braces - java

I am trying to run the below code with x =10 ."X is not equal to 10!" is getting printed. but As per documentation, the else belongs to the innermost if()? Also if we replace "1==2" in the if block with 1==1 then also "X is not equal to 10!" is getting printed.
I have corrected the code ..
Edit : Got the answer.
if(1==2)
if(x!=10)
System.out.println("X is equal to "+x);
else
System.out.println("X is not equal to 10!");

Indent correctly to see
if(1==2)
System.out.println(x);
if(x!=10)
System.out.println("X is equal to "+x);
else
System.out.println("X is not equal to 10!");
I think that answers it already.
But more detailed:
First if is not true, the first println does not get executed (apart from the described second version).
Second if is unconditionally evaluated, is not true, the else is executed.
Or ot reflect it on the quote, there is no "inner" if because there is no if enclosing any other if.
Or another aspect, you seem to think that the output is occurring because the first ifs condition is false, i.e. the else is attached to the first if. It is however attached to the second if because the conditional code influenced by the first if ends at the ;. To have more code influenced by the first if you could introduce a block of several lines, with a pair of {}.

your control structure is missing enclosing brackets. these are important to enclose the scope of your logic otherwise unless you're careful you'll end up with incorrect logic.
public class flow {
public static void main(String[] args) {
int x = 10;
if(1==2)
System.out.println(x); <--- this is 'dead code' will not be reached
if(x!=10)
System.out.println("x is equal to " + x);
else
System.out.println("x is not equal to 10!");
}
}
furthermore, your answer is printing 'x is not qual to 10!' in the console because your logic is evaluating the 'else' clause. the logic, if(x!=10) print equals to x, but if it is equal to 10 then print not equal to 10.

Please put open and close curly braces on your code:
if(1 == 2){
System.out.println(x);
if(x!=10){
System.out.println("X is equal to " + x);
} else {
System.out.println("X is not equal to 10!");
}
}
for more info: Is it bad practice to use an if-statement without brackets?

Related

integer comparison shows no output, why?

int a=10, b=5;
if(a>b)
{
if(b>5)
System.out.println("b is:"+b);
}
else
System.out.println("a is:"+a");
}
This code shows no output when running, why?
Your snippet annotated:
int a=10, b=5;
if(a>b) // is true (10>5)
{
if(b>5) // is false (5>5)
System.out.println("b is:"+b);
// no else case, so does nothing
}
else // never gets here
System.out.println("a is:"+a");
} // unmatched bracket
Make sure there’s no syntax errors in your full code (like unmatched brackets) and that there’s always an else case, be it for development purposes only.
That's dangling else ambiguity. You are matching wrong if clause with the else clause? It's a common error.
This is often due to poor formatting.
That's your code:
int a=10, b=5;
if(a>b)
{
if(b>5)
System.out.println("b is:"+b);
}
else
System.out.println("a is:"+a");
}
That's a properly formatted code:
int a=10, b=5;
if(a>b)
{
if(b>5)
System.out.println("b is:"+b);
}
else
System.out.println("a is:"+a");
}
See how each statement is indented. It's clear that the else clause is associated with the outer if. But, in your code it's hard to see.
Your IDE can properly format the code for you. If you are using Eclipse, for example, you can select your code and press Ctrl + I to format your code.
if(a>b) = true | No output
if(b>5) = false | No output (Reason: 5 is not greater than 5)
else block is not being executed
Your code shows no output because a > b but b = 5, not greater than. To solve this, change if(b>5) to if(b>=5).
This is another case where reformatting makes the question so much clearer.
int a=10, b=5;
if(a>b) { // 'true' - This block is executed
if(b>5) // 5 is not greater than 5, it's equal, so this isn't executed
System.out.println("b is:"+b);
} else { // This is not executed
System.out.println("a is:"+a);
}
When a bug gets confusing just take the program step by step and think as the compiler would. Also, I'd recommend forming a full block with { braces } for an else statement if you used braces for the if statement, it makes things tie together nicer and it's easier to read. Making sure things are indented properly also makes things easier to understand. Readability is important!
int a=10, b=5;
if(a>b)
{
if(b>5)
System.out.println("b is:"+b);
}
else
System.out.println("a is:"+a");}
In your code above In first if you are checking (a>b) i.e (10>5) the condition is true so execution of block inside first if is started.
In your second if condition (b>5) i.e (5>5) condition is false. So it terminates the program hence it doesn't displaying anything.
For better understanding I edit your code as below:
int a=10,b=5;
if(a>b) // This condition is true so this if block executed
{
if(b>5) // this is false so this block won't execute.
{
System.out.println("b is :"+b);
}
}
else // Alredy first if executed because true condition so this also not executing
{
System.out.println("a is :"+a);
}
// Thats why you don't get any output in this program.

Control if-else statements inside for loop

static void merge(int []part1,int []part2,int []array)
{
int index1=0;
int index2=0;
for(int k=0; k<array.length; k++)
{
if(index1==part1.length)
{
array[k]=part2[index2];
index2++;
System.out.println("fourth");
}
else if(index2==part2.length)
{
array[k]=part1[index1];
index1++;
System.out.println("third");
}
else if(part1[index1]<part2[index2])
{
array[k]=part1[index1];
index1++;
System.out.println("second");
}
else
{
array[k]=part2[index2];
index2++;
System.out.println("first");
}
}
}
The part1 and part2 lengths are 4,and the array length is 8. In this condition why is the "second" is the first to print and not the "first"?
The condition is all false, that is why the else is the first to print?
I am little confused about else if.
In a if(condition) else if(condition2) else ..., there is no first/second to be executed. Also this is not really java specific. Only the block for which the condition is true will be executed. Here you first have:
if(index1==part1.length)
=> index1 = 0
=> part1.length = 4
So this condition is false.
else if(index2==part2.length)
we have the exact same scenario here, condition is false
else if(part1[index1]<part2[index2])
here unless we know what's in the input arrays, we can't know if it's true of false, but based on your comment this condition is true, hence the code in this block is executed along with System.out.println("second");.
Think of what this code is trying to achieve (we're merging 2 sorted arrays into a third array that will be sorted as well), understand that it is within a loop, and for each loop iteration it is executing a different block depending on the conditions.
You print second in your third condition, that is, at the first for iteration, when the arrays have any elements in them AND part1[0] < part2[0]
When you chain if else the first block for which the condition is true, gets run, and no other.
if(a) {
x();
} else if(b) {
y();
} else if(c) {
z();
}
If a is true, x() is run, and no other methods.
If a is false and b is true, y() is run, and no other methods.
if a is false, b is false, c is true, z() is run, and no other methods.
It may help to realise that the above is equivalent to:
if(a) {
x();
} else {
if(b) {
y();
} else {
if(c) {
z();
}
}
}
That is literally how the compiler interprets it; however most human readers find the first version, with fewer braces and less indentation, easier to read.
In your code, if "second" is printed, we can be certain that the third condition is true.
The third condition is:
part1[index1]<part2[index2]
The first time around the loop, index1 and index2 are both zero, so this block runs when the first element of part1 is less than the first element of part2.
You could confirm this by adding another debugging println above "second":
System.out.println( "part1[" + index1 + "]=" + part1[index1]);
System.out.println( "part2[" + index2 + "]=" + part2[index2]);
System.out.println("second");
But note that debugging using println is a bad habit to get into -- learn to use a debugger as soon as practically possible.

While and do while loops

I'm new to this site and also very new to Java and I'm trying to understand the do while loops
Question: What is the output and why?
public class DoWhile {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("i is : " + i);
i++;
} while(i < 1);
}
}
I get that the output is "i is : 1" but I'm trying to understand why. It stops once it hits while because i isn't less that 1, right?
Just trying to get my head around it so any help will be appreciated.
Yes. Correct.
do { } while (condition);
This will perform the code at least once, regardless of the condition. After the first execution it will check the condition, which will evaluate to false (1 is not smaller than 1) and thus it will stop.
Yes, the output is 1 because in a do-while loop the statements within the do block are always executed at least once.
After the do block is executed the i value becomes 2 and the while block is not executed.
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
Yes, the output is
i is : 1
The do-while loop will always execute at least once, because the condition isn't evaluated before the loop is entered; it's only evaluated at the end of each iteration. This is in contrast to the while loop, whose condition is checked before the first iteration as well as after each iteration.
i is 1 at the start, then print occurs, then i is incremented to 2. Then the condition is evaluated -- it's false, so the loop terminates.
The output is just 1 becuase the do causes the loop to execute at least once, but the condition in the while doesn't aloow the loop to reiterate, because i is never less than 1
It is no more 1
public class DoWhile {
public static void main(String[] args) {
int i = 1; // i is 1
do {
System.out.println("i is : " + i); //still i is 1
i++; // this makes i = 2;
} while(i < 1);
}
}
if you notice the comments it is no more 1 after the first iteration

increment a number in java until it gets to 100 than decrement down to 0 continously

I'm making a game where there is a goalie. i want him to move back and forth forever. i have an int called goalieposx (goalie position on the x axis) and i want this is go up by 1 until it hits 200, then go down by one till its back a 0 and repeat. I've tried the folllowing
//this bit isnt in the method, its outside as global varibale
boolean forward=true
//this bit is in a method which is continiouly called nonstop
if (goalieposx<200){
forward=true;
}
else if (goalieposx>200){
forward=false;
}
System.out.println(forward);
if(forward=true){
goalieposx++;
System.out.println("forward");
}
else if (forward=false){
goalieposx--;
System.out.println("backwards");
}
}
this method is called continously. It prints true until it gets to 200, then it prints false. However, it always prints forward, never backward. So conclusion is: the boolean changes as expected but the first if is always called, it seems to ignore the condition
ive also tried this
if(forward = true){
if(goalieposx==200){
forward=false;
}
else{
goalieposx++;}
}
else{
if(goalieposx==0){
forward=true;
}
else{
goalieposx--;}
System.out.println(goalieposx);
}
but this doesnt work either, it prints 1 then 2 etc upto 200 then prints 200 forever. Anyone know how i can solve this? is an if statement the wrong idea altogether?
This is why you should never do comparison for boolean types in if, while, for, whatever. You have just done the assignment in your if statement:
if(forward=true)
the above if statement will always evaluate to true. The problem with this is, this compiles successfully in Java, as syntax wise it's alright. Compiler just checks the type of expression in if evaluates to boolean or not. And it does, so it's ok with it.
You need to do the comparison:
if(forward==true)
.. but as I said, you should not do comparison for boolean types. So, simply doing this:
if(forward)
would be enough.
You also don't need those else if in both the conditions. Just an else will work fine. Well, I don't understand the use of boolean variable at all. It seems like you don't need it. You can change your code to:
if (goalieposx<200){
// forward=true;
goalieposx++;
System.out.println("forward");
}
else {
// forward=false;
goalieposx--;
System.out.println("backwards");
}
What you were previously doing is, setting a boolean variable, based on a condition, and using that boolean variable as condition to execute another if-else block. Well, whatever you are executing in the 2nd if-else block, can simply be moved in the original if-else block, without taking the help of the middle-actor boolean variable.
if(forward=true) does not do what you thing it does.
In java = is the assignment operator and == is the comparison operator. What you are doing with that statement is saying "if assign forward to true" which will set forward to true and always return true.
What you mean to say is if(forward) and if(!forward).
In fact you don't need the else if just an else as if the boolean is not true it must be false.
A better way to do it is to get it to move to the left by adding a minus number, and to the right by adding a positive number. Here's an example of doing this with a loop:
for(int i = -10; i < 100; i++) {
xPosition += i;
}
This would add -10 then -9 etc. to the position.
In your if statements, you need to put two equal signs to check for equality.
if (forward == true){
// execute code
}
EDIT 1:
if (forward)
would be much simpler.
First let's examine what you have already written:
if (goalieposx<200){
forward=true;
}
else if (goalieposx>200){
forward=false;
}
The problem with this code being first is that it while it might set the direction to false once 'goalieposx' has reached 201, in the next call, it will set the direction back to true.
Instead, try using this clever alternative:
//This goes before the infinite loop method
counter = 0;
//Then in the infinite loop method
counter++;
if(counter > 100) {
counter = -100;
}
goalieposx = 100 + counter; //(this shifts counter from
// between -100 and 100 to 0 and 200)
The problem is you are setting the direction based on the value of the integer, instead of whether a condition has previously been met. Try this:
//this bit is in a method which is continiouly called nonstop
if (forward && (goalieposx>200)){
forward=false;
}
System.out.println(forward);
if(forward=true){
goalieposx++;
System.out.println("forward");
}
else if (forward=false){
goalieposx--;
System.out.println("backwards");
}
}

prefix and postfix increments while comparing variables

could someone explain why this code output is
not equals
not equals 2
in the first if statement it seems that a = 0 b/c is a postfix increment; therefore a will not increase untile next line; however, the two a's are not equal why? and in the second if when I run the debugger the value of a is 2, but the test is false, why?
public static void main (String[] args)
{
int a = 0;
if (a++ == a++) {
System.out.println("equals");
} else {
System.out.println("not equals");
}
if (++a == 2) {
System.out.println("equals 2");
} else {
System.out.println("not equals 2");
}
}
it's not that it waits until the next line. The == is a 'logical' operator so the expression on each side is evaluated first, each of which has the side-effect of incrementing the 'a' value. The result of the 1st increment is used on LHS, result of 2nd on RHS.
In these cases it matters not whether the operator is 'prefix' or 'postfix'
a++(post increment) would increment a first and then assign it to the variable. in your first case
(a++==a++) in the first post increment a value would be incremented by 1 first but not assigned yet, but when it reaches the second a++, now the a value is assigned and you are incrementing it again.
for example
if say a=0;
(a++==a++) would be (0==1)
so now the a value would be 2 after evaluating the if.
for your second case
(++a==2) here a would be incremented to 3 , (3==2) which is false thus the else if executed
EDIT: just realized you asked also for first not equals, this just answers the second one yet.
Because
a is already 2 (already incremented twice)
++a is 3 so
3 == 2 is false since prefix is applied before evaluation.

Categories

Resources