2

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.

2
  • println is a print line so look at that for a start. Commented Oct 12, 2016 at 15:57
  • I changed it to print() and that still does not fix the problem because I need them to each be on their own line Commented Oct 12, 2016 at 15:58

2 Answers 2

4

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I don't know why I did not try this!
2

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.