3
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?

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
aaa
  • 99
  • 1
  • 1
  • 7

4 Answers4

3

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");
 }
ajb
  • 31,309
  • 3
  • 58
  • 84
1

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

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 {}.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

The for loop logic must be contained in {}

Jakir00
  • 2,023
  • 4
  • 20
  • 32