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?????
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.
Re: Need Help on Looping Program!! Beginner!!
Once the where i%n does equal zero, it won't ever add 1 to i again. Also, when is the program exactly finished?
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?
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;
System.out.println("What is your number?");
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.
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.
Re: Need Help on Looping Program!! Beginner!!
And wrap your code in code tags for better readability.
Re: Need Help on Looping Program!! Beginner!!
once try this
Code :
import java.util.*;
...edited by moderator
or else according to your code
Re: Need Help on Looping Program!! Beginner!!
@rajivsomayaji, please read the forum rules and the following:
http://www.javaprogrammingforums.com...n-feeding.html