java作业整理

1. 编写一个程序,提示用户输入一个正整数,然后以降序显示其最小的因子。

要求:(1) 写出类名为(MinimalElements)且含有main方法的能完整运行的程序。

      (2) 求最小因子的方法getElements(int val)为静态,且在main方法中调用。

                   (3) 使用Stack类来保存最小因子,在main方法中输出Stack类型对象元素。

import java.util.Scanner;
import java.util.Stack;
public class MinimalElements {
       public static void main(String[] args){
    	   while(true){
    	   System.out.println("Enter a integer please:");
    	   Scanner input = new Scanner(System.in);
    	   int number = input.nextInt();
    	    
    	   if(number == 0){
    		   System.out.println("Already exit...");
    		   break;
}
    	   Stack stack = new Stack();
    	   stack = getElements(number);
    	   while(!stack.empty())
    	   System.out.print(stack.pop() + " ");
    	   System.out.println();
    	   System.out.println("If you want exit,input 0...");
    	   }
       }
       
       public static Stack getElements(int val){
    	   Stack stack = new Stack();
		for(int i = 2;i <= val; ){
			if(val % i == 0){
    			   stack.push(i);
    			   val /= i;
			}
			else if(val == 0)
				break;
    		   else
    			   i++;
    			   
    	   }
//    	   while(!stack.empty())
//    		   System.out.print(stack.pop() + " ");
		return stack;
       }
}


你可能感兴趣的:(java作业整理)