[英]System.out.println doesn't print a line with no parameters?
public class Test2 {
public static void mystery(int x, int y, boolean b, String s) {
System.out.println(x*3 + "..." + x/y);
if (b)
System.out.println("yes");
else
System.out.println("no");
for (int i = 2; i <= 5; i++)
System.out.print(2*i);
System.out.println();
System.out.println((double)(y/x));
System.out.println(s.substring(3,7));
} // end mystery
public static void main(String[] args) {
mystery(7,3,true,"freezing");
}
}
I'm a little confused and I think I'm missing something.我有点困惑,我想我错过了一些东西。 How come the output of the for loop in this code is 46810?
为什么这段代码中for循环的输出是46810? Shouldn't there be a line in between each of the numbers?
每个数字之间不应该有一条线吗?
It appears to me that you wanted your loop to look like this:在我看来,您希望循环看起来像这样:
for (int i = 2; i <= 5; i++)
System.out.print(2*i);
System.out.println();
But the for
only applies to the first statement.但是
for
仅适用于第一个语句。 To include multiple statements in the loop, you need to enclose the loop body in curly braces:要在循环中包含多个语句,您需要将循环体括在花括号中:
for (int i = 2; i <= 5; i++) {
System.out.print(2*i);
System.out.println();
}
It's best to always use curly braces when writing a for
loop, and also while
, do
, if
, and else
, even though the language allows you to have a body of just one statement without the curly braces.最好在编写
for
循环时始终使用大括号,以及while
、 do
、 if
和else
,即使该语言允许您在没有大括号的情况下只有一个语句的主体。 For example:例如:
if (b) {
System.out.println("yes");
} else {
System.out.println("no");
}
Not with System.out.print(2 * i);
不适用于
System.out.print(2 * i);
. . For the output you seem to expect change it to,
对于您似乎期望将其更改为的输出,
System.out.println(2 * i);
or add braces to your for
loop like,或将大括号添加到您的
for
循环中,例如,
for (int i = 2; i <= 5; i++){
System.out.print(2*i);
System.out.println();
}
Java loops aren't controlled by indentation, you need braces to contain more than one line. Java 循环不受缩进控制,您需要大括号来包含多于一行。
Try this:尝试这个:
for (int i = 2; i <= 5; i++)
{
System.out.print(2*i);
System.out.println();
System.out.println((double)(y/x));
System.out.println(s.substring(3,7));
}
When you are using the for
loop then it is recommended to put the code inside it in the curly braces {}
.当您使用
for
循环时,建议将其中的代码放在花括号{}
。
for 循环逻辑必须包含在{}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.