zoukankan      html  css  js  c++  java
  • 位数对调(代码重构)

    package com.ywx.count;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    /**
     * @author Vashon
     * date:20150410
     * 
     * 题目:位数对调:输入一个三位自然数,把这个数的百位与个位数对调,并输出对调后的数。
     * 
     * 分析:1.先确定输入的n是否是三位数,即n>99且n<=999
     *     2.位数对调:n=abc->cba=x,即百位数a=n整除100;十位数b=(n-a*100)整除10;个位数c=n除以10的余数;
     *     3.得对调后的数:x=c*100+b*10+a
     * 总结:结合对调计算方式和数据校验,对该程序进行重构后的结果。
     */
    public class Exchange {
    	public static void main(String args[]){
    		Input input=new Input();
    		int n=input.getInt("请输入一个三位数:", "输入的不是数字后不是又三位数字构成!请重新输入:");
    		int a,b,c,last=0;
    			a=n/100;
    			b=(n-a*100)/10;
    			c=n%10;
    			last=c*100+b*10+a;
    			System.out.println("对调后的数字为:"+last);
    	}
    }
    /**
     * 校验类
     * @author Vashon
     */
    class Input{
    	BufferedReader buf=null;
    	public Input(){
    		this.buf=new BufferedReader(new InputStreamReader(System.in));
    	}
    	public String getString(String info){
    		String str=null;
    		System.out.println(info);
    		try {
    			str=this.buf.readLine();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return str;
    	}
    	/**
    	 * 得到这个整数
    	 * @param info 提示消息
    	 * @param err  错误消息
    	 * @return
    	 */
    	public int getInt(String info,String err){
    		int temp=0;
    		String str=null;
    		boolean flag=true;
    		while(flag){
    			str=this.getString(info);
    			if(str.matches("^\d+$")){
    				temp=Integer.parseInt(str);
    				if(this.Validate(temp))
    				flag=false;
    			}else{
    				System.out.println(err);
    			}
    		}
    		return temp;
    	}
    	/**
    	 * 校验是否是三位数字构成
    	 * @param num
    	 * @return
    	 */
    	public boolean Validate(int num){
    		boolean flag=false;
    		if(num>99&&num<=999){
    			flag=true;
    		}
    		return flag;
    	}
    }
    

    
        
            

    版权声明:本文为博主原创文章,未经博主允许不得转载。

    Stay Hungry, Stay Foolish, Walking in Life
  • 相关阅读:
    Ubuntu16.04 + OpenCV源码 + Qt5.10 安装、配置
    DML和DQL
    初识MySql
    表单校验
    使用jQuery操作DOM
    jQuery中的事件与动画
    jQuery选择器
    初识jQuery
    JavaScript对象及初识OOP
    JavaScript操作DOM对象
  • 原文地址:https://www.cnblogs.com/ywx-vashon/p/4895781.html
Copyright © 2011-2022 走看看