See post blow.
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
See post blow.
Last edited by KevinGreen; October 31st, 2009 at 07:28 PM.
After much screaming, I get them to sort out a little; but I'm having trouble with the print. I want:
Line 1: 2, 4, 6, 8...
Line 2: 22, 24, etc etc.
How do I insert the Line 1: text in the if else format, without causing the if else to print line 1 for every number it kicks out?
public class EvenNums { public static void main(String[] args) throws Exception { int i = 2; int limit1 = 21; int limit2 = 41; int limit3 = 61; int limit4 = 81; for (i = 2; i < 100; i++) { if ((i % 2) == 0 && i < limit1) { System.out.print(i); } else if ((i % 2) == 0 && i < limit2) { System.out.print(i); } else if ((i % 2) == 0 && i < limit3) { System.out.print(i); } else if ((i % 2) == 0 && i < limit4) { System.out.print(i); } } }
Last edited by KevinGreen; October 31st, 2009 at 07:28 PM.
If I understand your question correctly: your for loop can be written differently and increment by 2 rather than 1. This would remove having to use modulus to check for even numbers. You can create a small look up table to print the lines. Of course new lines and commas need to be added to the appropriate places get the output you want.
String line[] = {"Line 1: ", "Line 2: ", "Line 3: ", "Line 4: ", "Line: 5 "}; int mark = 0; for (int i = 2; i < 100; i+=2) { if ( i % 20 == 2 ){ System.out.print(line[mark]); mark++; } System.out.print(i); System.out.print(" "); }