PDA

View Full Version : Java loops help


TheKick
07-05-2005, 01:11 AM
Ok I am new to Java and am trying to nail down use of loops. I am trying to have my program output all the even numbers from 0-500 displaying 5 numbers per line on a JOptionPane.showMessageDialog screen. I can get it to output one number each output box but you need to keep hitting ok. I was thinking of using modulus in an if loop.

Something like
If (count % 5 == 0);
temp = temp + "/n";
mabey?


Here is what I have at the moment. I am really stuck on how to implement the return character.

import javax.swing.JOptionPane;

public class Counting
{
public static void main(String args[])
{
String temp;
int count=0;

while (count <= 400)
{
JOptionPane.showMessageDialog(null, "The output is "+ count);
count = count + 2;
}
if (count % 5 == 0);
temp = temp + "/n";
System.exit(0);
}

}

Brandoe85
07-05-2005, 02:33 AM
Yes, you have the right idea, but the reason you have to hit ok everytime is because your JOptionPane.showMessageDialog(null, "The output is "+ count); is inside your loop, therefore it's going to be called each time the loop iterates.

As I assume this is a homework assignment i'll try to give some pointers. You might want to add your count variable into your temp variable each time the loop iterates, then do a check wheather it's been 5 numbers, then add the newline character onto the temp variable and then after your loop, show your JOptionPane.showMessageDialog(null, "The output is"+ temp);

TheKick
07-05-2005, 06:01 AM
I tried going about this a different way. I tried to use a for loop where I would set up my counter then assign it to output then have the endline segment all in the for loop. Not sure if this is making more work for myself or not.

import javax.swing.JOptionPane;

public class Counting
{
public static void main(String args[])
{
int value;
String output = "";
String endline = "";

for ( int counter = 0; counter <=400; counter = counter + 2);
{
counter += output + " ";

if ( counter % 5 ==0 )
endline += "\n";
}

JOptionPane.showMessageDialog (null, output);

System.exit(0);
}

}

Brandoe85
07-05-2005, 09:13 AM
Well I think your first approach was pretty close. Heres what I mean:

Psuedo
while your counter is <= 400
add your counter onto your temp string
check to see if it's been five lines
if it has
add the \n onto your temp string
End if
increment your counter variable
End while
display your JOptionPane message box
End Psuedo