lundi 15 février 2021

Sum of digits using Java

I am a beginner in programming and I am trying to output the sum of digits of the user input using Java.

The code should say certain message based on the length of the digit and end it when user types a blank space.

My code executes correctly. However, it only works on the first input. After the first input, I get an error message.

How can I possibly fix my code, so that my while loops work efficiently?

    //scanner
    Scanner input = new Scanner (System.in);

    //ask user for a credit card number
    System.out.print("Enter a credit card number (enter a blank line to quit): ");
    String userNum = input.nextLine();
    
    
    //length and last char of string
    int len = userNum.length();
    char lastDigit = userNum.charAt(len-1);
    
    
    //initial values
    int sumOfDigits = 0;
    int strNum = 0;
    int i;

    //loops
    while (len > 0) {
        if (len == 16) { //when length equals 16
            for (i = 0; i < 15; ++i ) { //calculates sum of digits
                String s = userNum.substring(i, i+1);
                strNum = Integer.parseInt(s);
                sumOfDigits = sumOfDigits + strNum;
            }
            System.out.println("DEBUG: Sum is " + sumOfDigits);
            System.out.println("Check digit is: " + lastDigit);
            System.out.println();    
            System.out.print("Enter a credit card number (enter a blank line to quit): ");
            userNum = input.next();
        }
        else if (userNum.equals("")) { //when user types blank space
            System.out.println("Goodbye!");
        }
        else { //when user digit is not 16, nor types a blank space
            System.out.println("ERROR! Number MUST have exactly 16 digits."); 
            System.out.println();
            System.out.print("Enter a credit card number (enter a blank line to quit): ");
                userNum = input.next();
        }
    }
    
    
    
    //input close
    input.close();

}

Aucun commentaire:

Enregistrer un commentaire