Changing Integer Value inside an if and else statement

时间:2017-12-18 05:02:47

标签: java for-loop if-statement

I'm trying to create some Java code in an if-and-else statement that goes between the two. When I run the code, the expected output should be: "hello world hello world" but all I get is "hello hello hello hello"

I have no clue what I'm doing wrong over here. Can somebody please tell me the problem?

int p = 1;

for (int i = 1; i < 5; i++) {
    if (p == 1) {    
        System.out.println("hello");
        p = 2;
    } else {
        System.out.println("world");
        p = 1;
    }
}

3 个答案:

答案 0 :(得分:2)

It isn't all the code you have in your program, but look here:

    else
        System.out.println("world");
    p = 1;
}

Last curly brace doesn't belong to the else part of if-else statement, it belongs to the for loop that encloses an if-else part - improve formatting of your code and you will see the difference. Your else part isn't surrounded with curly braces, so only the first line after else word is executed when the second condition is to be performed.

答案 1 :(得分:0)

according to @ajb comment, you just move p = 1 to else block:

for (int i = 1; i < 5; i++) {
   if (p == 1) {
       System.out.print("hello");
       p = 2;
   } else {
      System.out.print("world\n");
      p = 1;
    }
}

答案 2 :(得分:0)

You are missing a curly brace on the else block.

int p = 1;

for(int i = 1; i < 5; i++){
  if (p == 1){    
      System.out.println("hello");
      p = 2;
  }
  else {
      System.out.println("world");
      p = 1;
  }
}