7.8-JAVA中判断输入数字的位数、String转Int的方法
题目要求:
1)、输入四位会员卡号
2)、判断会员卡号的位数
3)、若卡号输入大于或小于4位,则重新输入
4)、分别输出四位数字的个、十、百、千位
判断会员卡号位数的代码如下:
lengh = id.lenth()//识别字符串长度
若卡号位数出错则重新输入,使用do…while…循环
do{
if(length==0){
System.out.print("输入会员卡号:");
}else{
System.out.print("重新输入会员卡号:")
}
Scanner sc = New Scanner(System.In);
id = sc.next();
length = id.length();
}while(length!=4)
代码如下:
public class test1 {
public static void main(String[] args) {
String id = null;
int length = 0;
do {
if (length==0){
System.out.println("请输入四位会员卡号:");
}else {
System.out.println("请重新输入四位会员卡号:");
}
Scanner sc=new Scanner(System.in);
id = sc.next();
length = id.length();
}while (length!=4);
System.out.println("会员卡号是:"+id);
int num = Integer.parseInt(id);
int gw = num%10;
int sw = num/10%10;
int bw = num/100%10;
int qw = num/1000%10;
System.out.println("千位:"+qw+"百位:"+bw+"十位:"+sw+"个位:"+gw);
int sum=gw+sw+bw+qw;
System.out.println("会员卡号"+id+"各位之和:"+sum);
if (sum>20){
System.out.println("恭喜您,您中奖了!");
}else {
System.out.println("您没有中奖!");
}
}
}
注意:
1)id 只能定义成string类型,再用length = id.length(),语句可以判断id字符串的长度,若id定义成int类型,输入0000时,会认为其没有位数,位数是0.
2)由于开始定义了id是字符串类型,在后来计算其个、十、百、千、位数字的时候需要将string转换成int:
int num = Integer.parseInt(id);