See post blow. :(
Printable View
See post blow. :(
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?
Code :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); } } }
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.
Code :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(" "); }