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? 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. 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 example:
if (b) {
System.out.println("yes");
} else {
System.out.println("no");
}
Not with 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 (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.
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 循环逻辑必须包含在{}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.