English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have this code to find the smallest factors of any number that is inputted but I need to know how to get it to print an interger only once. ex. if I put in 120 I get 2,2,2,3,5. But I only the output to show 2,3,5 someone please help!!


import javax.swing.JOptionPane;

public class Exercise4_16 {
// Main method
public static void main(String args[]) {
// Prompt the user to enter a positive integer
String intString = JOptionPane.showInputDialog(
"Enter a positive integer:");

// Convert string to int
int number = Integer.parseInt(intString);

// Find all the smallest factors of the integer
System.out.println("The factors for " + number + " is");
int factor = 2;
while (factor <= number) {
if (number % factor == 0) {
number = number / factor;
System.out.println(factor);
}
else {
factor++;
}
}
}
}

2007-02-14 15:42:39 · 2 answers · asked by Fresh Java meat 1 in Computers & Internet Programming & Design

2 answers

As you find your factors, don't print them immediately. Put them into a Set. A "Set" is a collection that does not contain or allow duplicates. There are a number of implementations of the Set interface in the java.util package, but if you use the java.util.TreeSet class, the values stored will be sorted by natural order. Note: you can't store primitives in a Set, so you will need to wrap them as Integer objects).

2007-02-15 04:38:43 · answer #1 · answered by vincentgl 5 · 0 0

I think the problem is that you are only increasing factor in the else statement. It needs to be increased in the if statement as well.
Say you have 16. It will go through. Number will become 8. But factor will still be 2. 2 will go through as a factor of 8 as well, which is why you're seeing repeating numbers. See what I'm saying?

2007-02-15 00:15:35 · answer #2 · answered by LexiSan 6 · 0 0

fedest.com, questions and answers