# Need Help on Looping Program!! Beginner!!

• February 28th, 2012, 08:30 PM
PinkFly
Need Help on Looping Program!! Beginner!!
I'm having trouble on a program where I am supposed prompt the user for a positive integer and then displays those integers.

My teacher told me to use this:
Initialize a counter to 2
while the counter is less than or equal to the number
if the counter divides the number evenly
display the counter
divide the number by the counter to get a new number
else increment counter by 1

This is what I tried:

Code Java:

```import java.util.Scanner; public class PrimeFactors {   public static void main(String []args) {   Scanner input = new Scanner(System.in);   int n; int i;   System.out.println("What is your number?"); n = input.nextInt();   for(i = 2;i<=n;i++) while (i <= n) { if(i%n == 0) System.out.println(i); else i++; }     }     }```

It has an infinite loop. Help?????
• February 29th, 2012, 07:50 AM
Norm
Re: Need Help on Looping Program!! Beginner!!
To see what the code is doing, add some printlns that print out the values of i and n as it executes.
• February 29th, 2012, 08:52 PM
aesguitar
Re: Need Help on Looping Program!! Beginner!!
Once the
Quote:

Code :

`if(i%n == 0)`

where i%n does equal zero, it won't ever add 1 to i again. Also, when is the program exactly finished?
• March 1st, 2012, 06:03 AM
Mr.777
Re: Need Help on Looping Program!! Beginner!!
Code :

```while (i <= n)   { if(i%n == 0) System.out.println(i); else i++; }```
Look carefully. When your program is going to else part? What is the value of i? Why doesn't it change itself?
• March 1st, 2012, 06:34 PM
PinkFly
Re: Need Help on Looping Program!! Beginner!!
import java.util.Scanner;
public class PrimeFactors {

public static void main(String []args) {

Scanner input = new Scanner(System.in);

int n;

n = input.nextInt();

for(int i = 2;i<=n;i++)
while (i <= n)
{
if(i%n == 0){
System.out.println(i);
n=n/i;
}
else
i++;

}

}

}

Okay, I did this. However it just displays the number entered.
• March 1st, 2012, 06:42 PM
Norm
Re: Need Help on Looping Program!! Beginner!!
Did you try this:
To see what the code is doing, add some printlns that print out the values of i and n and (i%n) as it executes.

The print out will show you what the code is doing. You need to understand what the code is doing if you want to be able to change it to do what you want it to do.
• March 2nd, 2012, 06:22 AM
Mr.777
Re: Need Help on Looping Program!! Beginner!!
• March 3rd, 2012, 11:15 PM
rajivsomayaji
Re: Need Help on Looping Program!! Beginner!!
once try this
Code :

```import java.util.*; ...edited by moderator```

or else according to your code

Code :

`...`
• March 4th, 2012, 12:05 AM
copeg
Re: Need Help on Looping Program!! Beginner!!