前言
笔试的时候碰到了这道题,当时写的不怎么好,就想着回来自己再写写,看了别人写的感觉都有点问题
就自己再写一下了(新手小白,代码有待优化)
代码
import java.util.Arrays;
import java.util.Scanner;
public class demo2 {
public static void main(String[] args) {
//将一个正整数 n 各个位置的数字拆分,再存储到数组中
//定义输入函数
Scanner scanner = new Scanner(System.in);
//首先判断 n的位数
System.out.print("请输入一个正整数(范围0~9999999):");
try {
//接收正整数n
int n = scanner.nextInt();
int m = n;
int count=1;
if(n<0||n>9999999){
System.out.println("输入超出范围");
}else if(n==0){
count = 1;
}else {
while(n!=0){
n=n/10;
if(n==0) {
break;
}
count++;
}
}
// System.out.println("n是"+count+"位数");
int[] a =new int[count];
System.out.println("这是一个"+a.length+"位数");
// System.out.println(Math.pow(10,count));//结果为double型,所以需要强制类型转换为int型再进行计算
for(int i=0,j=count;i<count;i++,j--){//为了保持i<count的count不变,用j来代替count
a[i] = m/(int)Math.pow(10,j-1);
m %= (int)Math.pow(10,j-1);
//当m<10代表仅剩最后个位数字,则直接跳出循环
if(m<10){
a[i+1] = m;
break;
}
}
System.out.println(Arrays.toString(a));
}catch (Exception e){
System.out.println("请输入正确格式的数据");
e.printStackTrace();
}
}
}
思路
假设n为987,先将9提出,放到数组中,再看剩下的87,进行下一次循环,直到剩最后一位,跳出循环
总结
遇到的知识点:
Scanner类
try catch语句
循环语句
math函数和强制类型转换
取整和取余的灵活运用