Reputation: 173
I'm getting my loop to print the integers 1-7 in vertical order. So like
1
2
3
4
5
6
7
That part works fine. Now I also need it to print next to it if the integer is divisible by 3. My code is as follows
for (int n = 1; n < 8; n++){
System.out.println(n );
if (n % 3 == 0){
System.out.print("divides evenly into 3");
}
}
Now my output looks like
1
2
3
divides evenly into 34
5
6
divides evenly into 37
I need the divides evenly part to be on the same line as 3 and 6. Not the line after. Anyone have any insight as to what I'm writing wrong here in my code? I am using Java.
Upvotes: 2
Views: 42
Reputation: 140504
Tim's answer is fine; here's an slight variation that avoids repeating the printing of n
:
for (int n = 1; n < 8; n++) {
// Using print instead of println doesn't insert the newline.
System.out.print(n);
if (n % 3 == 0) {
System.out.print(" divides evenly into 3");
}
// When there's nothing more to print on the line, now add the
// newline.
System.out.println();
}
Upvotes: 2
Reputation: 522441
Just add an else
condition:
for (int n = 1; n < 8; n++) {
if (n % 3 == 0) {
System.out.println(n + " divides evenly into 3");
}
else {
System.out.println(n);
}
}
Upvotes: 4