计算器的新功能

题目描述

当你学一些可视化程序设计语言时,老师经常会让你设计并且编程做出一个计算器,这时也许你会仿照windows系统自带的计算器外观和功能去设计,但是现在老师要你多做出一个有新功能的计算器,实现当输入一个数时,能够将这个数分解成一个或多个素因子乘积的形式,并按素因子的大小排列显示出来。大家对计算器中数的表示应该很清楚的。下面显示出了0 — 9这十个数字的表示形式。每个数字都占据5 * 3大小的字符区域



import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class Main {

	public static void main(String[] args) 	{
		Scanner scanner=new Scanner(System.in);
		int n;
		boolean[] isPrime;
		List<Integer> list;
		while(scanner.hasNext()){
			n=scanner.nextInt();
			list=new ArrayList<Integer>();
			isPrime=checkPrime(n);
			int temp=n;
			if(!isPrime[n]){ //n不是质数
				for(int i=2;i<=n;i++){
					if(isPrime[i]){ //分解因数
						while(temp%i==0){
							list.add(i);
							temp=temp/i;
						}
						if(temp==1){ //质数分解已经完成
							break;
						}
					}
				}
			}else{ //n是质数
				list.add(n);
			}
			print(list);
		}
	}
	
	public static boolean[] checkPrime(int n){ //筛选法求素数
		boolean[] isPrime=new boolean[n+1];
		for(int i=3;i<=n;i=i+2){
			isPrime[i]=true;
		}
		for(int i=3;i<n;i=i+2){
			if(isPrime[i]){
				for(int j=i+i;j<=n;j=j+i){
					isPrime[j]=false;
				}
			}
		}
		if(n>1){
		   isPrime[2]=true;
		}
		return isPrime;
	}
	
	//输出字符串
	public static void print(List<Integer> list){
		String[][] chars= { {" - ","| |","   ","| |"," - "},
		                    {"   ","  |","   ","  |","   "},
		                    {" - ","  |"," - ","|  "," - "},
		                    {" - ","  |"," - ","  |"," - "},
		                    {"   ","| |"," - ","  |","   "},
		                    {" - ","|  "," - ","  |"," - "},
		                    {" - ","|  "," - ","| |"," - "},
		                    {" - ","  |","   ","  |","   "},
		                    {" - ","| |"," - ","| |"," - "},
		                    {" - ","| |"," - ","  |"," - "}		                    
		      };

		String temp;
		String[] str;
		int num;
		int size=list.size();
		StringBuilder[] lines=new StringBuilder[5];
		for(int i=0;i<5;i++){
			lines[i]=new StringBuilder();
		}
		
		for(int i=0;i<size;i++){
			temp=Integer.toString(list.get(i));
			for(int j=0;j<temp.length();j++){
				num=temp.charAt(j)-'0';
				str=chars[num];
				for(int k=0;k<5;k++){
					lines[k].append(str[k]);
				}
			}
			if(i!=size-1){
				for(int k=0;k<5;k++){
					if(k!=2){
					  lines[k].append(" ");
					}else{
					  lines[k].append("*");
					}
				}
			}
		}
		for(int i=0;i<5;i++){
			System.out.println(lines[i].toString());
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值