7.8-The method of judging the number of digits of the input number, String to Int in JAVA

7.8-The method of judging the number of digits of the input number, String to Int in JAVA

Question requirements:
1), enter the four-digit membership card number
2), determine the digits of the membership card number
3), if the card number is greater than or less than 4 digits, re-enter
4), output the four-digit number one, ten, hundred, Thousands

The code for judging the digits of the membership card number is as follows:

lengh = id.lenth()//识别字符串长度

If the digits of the card number are wrong, re-enter, use do...while... loop

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)

code show as below:

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("您没有中奖!");
        }

    }
}

note:

1) id can only be defined as string type, and then use length = id.length(), the statement can judge the length of id string, if id is defined as int type, when input 0000, it will be considered that it has no digits, and the number of digits is 0.
2) Since id is defined as a string type at the beginning, it is necessary to convert string to int when calculating its one, ten, hundred, thousand, and digits later:

int num = Integer.parseInt(id);

Guess you like

Origin blog.csdn.net/qq_42005540/article/details/107202277
Recommended