java - StackOfIntegers Giving Weird Results -


i have issue making code returns prime factorization of integer. know code giving right factors, required use stackofintegers class.

the stackofintegers class not seem handle duplicates well. when input 120, prime factors 5, 3, , 2 returned. output missing 2 other 2's.

public class test {     public static void main(string[] args) {         scanner input = new scanner(system.in);         system.out.print("enter number: ");         int number = input.nextint();         stackofintegers stack = new stackofintegers(1);         int factor = 2;         while (true) {             if (number % factor == 0) {                 number = number / factor;                 stack.push(factor);             }             if (factor > number) {                 break;             }             if (number % factor != 0) {                 factor++;             }             if (number < 2) {                 break;             }         }         system.out.println("\nprime factors: ");         for(int = 0; < stack.getsize(); i++) {             system.out.println(stack.pop());         }         input.close();     } } 
class stackofintegers {     private int[] elements;     private int size;     public static final int max_size = 16;      /** construct stack default capacity 16 */     public stackofintegers() {         this(max_size);     }      /** construct stack specified maximum capacity */     public stackofintegers(int capacity) {         elements = new int[capacity];     }      /** push new integer top of stack */     public int push(int value) {         if (size >= elements.length) {             int[] temp = new int[elements.length * 2];             system.arraycopy(elements, 0, temp, 0, elements.length);             elements = temp;         }          return elements[size++] = value;     }      /** return , remove top element stack */     public int pop() {         return elements[--size];     }      /** return top element stack */     public int peek() {         return elements[size - 1];     }      /** test whether stack empty */     public boolean empty() {         return size == 0;     }      /** return number of elements in stack */     public int getsize() {         return size;     } } 

the problem incrementing i still comparing current size of stack, decreasing in each iteration well.

you can store size of stack in new variable size prior for loop, or can have while loop, , while stack not empty, pop , print element.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -