I tried to make a program that would give the whole factors for an inputed number. When i run it throught the command prompt it gives me a bunch of 1's, how do I make it to print each factor only once?

import java.util.Scanner;

public class Factors
{
    public static void main(String args[])
    {
        // Create a Scanner so we can get input from the user.
        Scanner input = new Scanner(System.in);
        int numbertofactor; //number they enter for integers
        int total; //number divided by each under it

        //welcome 

        System.out.print("Welcome! This program determines factors for Please enter an integer:");
        numbertofactor = input.nextInt();

        if (numbertofactor>0)
            {
                for (int counter = numbertofactor; counter>0; counter--)
                {
                    total = numbertofactor/counter;
                    if(numbertofactor%total == 0)
                    {
                        System.out.println(+total);
                    }
                }
            }
        else if(numbertofactor<0)
            {
                while (numbertofactor<1)
                {
                    System.out.print("Please enter a vaild factor.");
                }
            }
    }
}


C:\Users\jorda\Documents\CSCI201\Assignment3>java Factors

This is what I get when I put it in the comman prompt:

Welcome! This program determines factors for Please enter an integer:15
1
1
1
1
1
1
1
1
3
3
5
15

Recommended Answers

All 2 Replies

the problem is with the variable you call "total".
Your loop sets total to 15/15 then 15/14, then 5/13 etc - which in integer arithmetic keeps giving you 1's
I don't undersatnd what that variable is for anyway. In pseudo-code all you need is

for possible = 2 to (number-1) // 1 and number don't count as  factors
   if  (number modulo possible) == 0 then possible is a factor

Because in Java, int stores a number, not a decimal. When you divide an int with another int, the result will be a number (no decimal). You should read more on Java data type. You may use float instead, but then you will have to be careful on rounding error (shouldn't directly compare a divided result to 0).

Edited: Didn't see James answer, so mine looks redundant :P I hate this new look!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.