在if和else语句中更改整数值
问题描述:
我试图在两者之间的if-and-else语句中创建一些Java代码。当我运行代码时,预期输出应该是:“hello world hello world”,但我得到的是“hello hello hello hello”在if和else语句中更改整数值
我不知道我在这里做错了什么。有人可以告诉我这个问题吗?
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;
}
}
答
根据@ajb评论,你只需动p = 1
到else
块:
for (int i = 1; i < 5; i++) {
if (p == 1) {
System.out.print("hello");
p = 2;
} else {
System.out.print("world\n");
p = 1;
}
}
答
这是不是所有你的代码在你的程序,但看看这里:
else
System.out.println("world");
p = 1;
}
最后的大括号不属于if-else
声明的else
部分,它属于for
循环,其中包含if-else
部分 - 改进代码的格式,您将看到不同之处。您的else
零件没有用花括号包围,因此只有在执行第二个条件时执行else
字后的第一行。
答
您在else块上缺少大括号。
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;
}
}
你确定这是打印? –
检查你的花括号 – ajb
顺便说一下,标准的缩进实践是'for'块中的所有内容都应该缩进到'for'的右侧。在这里,你有第一个'if'开始于'for'的同一列,而不是缩进它。如果你缩小了它,你可能会自己发现问题。 – ajb