简体   繁体   中英

How do I get the rightmost digits for step 1? Then how do I get the digits that weren't included for step 2?

import java.util.Scanner;

public class Ass. {

public static void main(String[] args) {
    /*blanca 10/08/20
     * 3.Following is a fun algorithm of three steps to check whether a given 8 digit number is acceptable.
     * step1: starting from the rightmost digit,form the sum of every other digit. 
     * - For example the number is 12345658, this sum is 8+6+4+2 = 20.
     * step2: double each of the digits that were not included in the preceding step; add all digits of the resulting number. 
     * - For the example number above,doubled digits would be 10,10,6,2. Adding those digits will yield (1+0+1+0+6+2)10.
     * step3: Add the sum of the numbers in step1 and step2. if the last digit of that number is 0, the number is acceptable, not otherwise.
     * Your program should read an 8 digit number and output whether it is acceptable or not.
     */
    //declare
    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;
    int digits = 0;
        
    Scanner data = new Scanner(System.in);
    System.out.println("Enter a card number");
    digits = data.nextInt();
    //step 1 
    sum1 = digits%10;
    // step 2
    sum2 = digits%100;
    //step 3 
    sum3 = sum1 + sum2;
    if (sum3 = 0){
        System.out.println("Acceptable");
    }
    else 
    {
        System.out.println("Unacceptable");
        }

I saw some other questions and saw that the place value (like %10) is suppose to give the digits but I don't know how to change it depending on the question?

Here are some suggestions.

  1. To get the least significant digit, you use the remainder operator (%) with 10.
  2. To get the next digit, you divide the original number by 10 and apply the remainder operator to the quotient.
  3. For every other digit you need to apply the remainder operator and the division operator after multiplying the digit by 2. So 14 would be 1 + 4 which you should be able to figure out just like above.
  4. You can either continue this until your starting number is 0. Or repeat in a loop 4 times, getting two digits per loop and performing the appropriate summing operations.
  5. When done you simply test the result for the desired value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM