java经典问题——求正整数的位数

题目:给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。 


public class Number {

	int number;
	State current;
	int count;
	int[] charInNumber;
	
	public Number() {
		current = new OneState();
	}

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public State getCurrent() {
		return current;
	}

	public void setCurrent(State current) {
		this.current = current;
	}
	
	public void getCount(){
		current.getCount(this);
	}
	
	//求每位数字
	public void getChars(){
		charInNumber = new int[count];
		int temp = number;
		if(count >= 2){
			for(int i = 0; i < count; i ++){
				charInNumber[i] = temp / (getValue(count - 1 - i));
				temp = temp % (getValue(count - 1 - i));
				if(temp < 10){
					charInNumber[i + 1] = temp;
					break;
				}
			}
		}else{
			charInNumber[0] = temp;
		}
		
		
	}
	
	//求十的阶乘,感觉好蠢的方法
	public int getValue(int count){
		int value = 1;
		for(int i = 0; i < count; i ++){
			value = value * 10;
		}
		return value;
	}
}

public abstract class State {

	public abstract void getCount(Number number);
	
	
}

public class OneState extends State {

	@Override
	public void getCount(Number number) {
		if(number.getNumber() < 10 ){
			number.count = 1;
			number.getChars();
		}else{
			number.setCurrent(new TwoState());
			number.getCount();
		}
	}

}

public class TwoState extends State {

	@Override
	public void getCount(Number number) {
		if(number.getNumber() < 100){
			number.count = 2;
			number.getChars();
		}else{
			number.setCurrent(new ThreeState());
			number.getCount();
		}
	}

}

public class ThreeState extends State {

	@Override
	public void getCount(Number number) {
		if(number.getNumber() < 1000){
			number.count = 3;
			number.getChars();
		}else{
			number.setCurrent(new FourState());
			number.getCount();
		}
	}

}
public class FourState extends State {

	@Override
	public void getCount(Number number) {
		if(number.getNumber() < 10000){
			number.count = 4;
			number.getChars();
		}else{
			number.setCurrent(new FiveState());
			number.getCount();
		}
	}

}

public class FiveState extends State {

	@Override
	public void getCount(Number number) {
		if(number.getNumber() < 100000){
			number.count = 5;
			number.getChars();
		}
	}

}

public class Practise24 {

	private void getResult(){
		System.out.println("请输入一个不多于5位的正整数");
		Scanner scan = new Scanner(System.in);
		int input = scan.nextInt();
		Number number = new Number();
		number.setNumber(input);
		number.getCount();
		
		System.out.println(number.getNumber() + " 是 " + number.count +"位数");
		
		System.out.println();
		for(int i = number.count - 1; i >= 0; i --){
			System.out.print(" "+number.charInNumber[i]);
		}
	}
	
	public static void main(String[] args) {
		(new Practise24()).getResult();

	}

}


你可能感兴趣的:(java)