Lucky draw, if the sum of the entered membership card numbers is 20, the member is a lucky user

There are two ways to solve

  1. Solve using arrays
  2. Solve using operators

1. Use an array to solve
Use the Scanner class to get the input value, convert it into a string array, and then convert the string array into a numeric array for summing!
The core code is as follows:

 boolean isWin ;
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入一个整数:");
        String num = scanner.nextInt()+"";    // 输入整数,转为字符串
        String[] nums = new String [num.length()];
        for (int i = 0; i < num.length(); i++) {
    
    
            nums[i] = num.charAt(i)+"";  // 将输入的整数转化为字符串数组
        }
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
    
    
            sum += Integer.parseInt(nums[i]);    // 将数组内的字符串强转为整数,然后再相加。
        }
        if (sum == 20)
        {
    
    
            isWin = true;
        }
        else
        {
    
    
            isWin = false;
        }

        System.out.println("会员卡号"+num+"各位之和:"+sum);
        System.out.println("是幸运用户嘛?"+isWin);

2. Use operators to solve

boolean isWin;
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你的会员卡号:");
        int num = scanner.nextInt();

//        因为已经知道了会员卡号为四位数,所以我们可以使用运算符去对他们进行分解,一一求出各个位上的数字
        int gewei = num % 10;
        int shiwei = num % 100 /10;
        int baiwei = num % 1000 /100;
        int qianwei = num / 1000;

        int sum = gewei + shiwei + baiwei + qianwei;

        if (sum == 20)
        {
    
    
            isWin = true;
        }
        else
        {
    
    
            isWin = false;
        }
        System.out.println("会员卡号"+num+"的和为:"+sum);
        System.out.println("是幸运用户?"+isWin);

Guess you like

Origin blog.csdn.net/heart_is_broken/article/details/120804878