4.给定一个正整数m,统计m的位数,分别打印每一位数字,再按照逆序打印出各位数字。 要求:m定义为类的属性,需定义构造函数为m赋值;当m大于99999时,输出错误信息“the number is too large”,不再执行。
package a; public class ShuZi { int m; public int getM() { return m; } public void setM(int m) { this.m = m; } public void shu() { System.out.println("输入的数字是:"+m); if(m>99999) { System.out.println("The number is too large"); } else if(m<0) { System.out.println("必须输入正整数"); } else { System.out.println("m的位数为:"+String.valueOf(m).length()+"位"); System.out.print("逆序打印数字:"); for(int i=String.valueOf(m).length()-1;i>=0;i--) { System.out.print(String.valueOf(m).substring(i,i+1)); } } } public static void main(String[] args) { ShuZi shu=new ShuZi(); shu.setM(3684); shu.shu(); } }
m的值无限制时
package a; public class ShuZi { String m; public String getM() { return m; } public void setM(String m) { this.m = m; } public void shu() { System.out.println("输入的数字是:"+m); if(m.substring(0,1).equals("-")) { System.out.println("必须是正整数"); } else { System.out.println("数字的位数为:"+m.length()+"位"); System.out.print("逆序打印数字:"); for(int i=m.length()-1;i>=0;i--) { System.out.print(m.substring(i,i+1)); } } } public static void main(String[] args) { ShuZi shu=new ShuZi(); shu.setM("325340069646798572422365125"); shu.shu(); } }