How to make while loop check if there are 16 digits in a string

TragicFlawz :

How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!

import java.util.Scanner;

public class LuhnAlgorithm {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
        String nums = input.nextLine();

        int i = 0;
        char chk = nums.charAt(15);

        while(!nums .equals("") ) {

            if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
                System.out.println("ERROR! Number MUST have exactly 16 digits.");
            }

            int sum = 0;
            for( i = 0; i < 15; i++) {  
                char numc = nums.charAt(i);
                int num = Character.getNumericValue(numc);
                if ( i % 2 == 0 ) {
                    num = num * 2;
                    if ( num >= 10) {
                        num = num - 9;
                    }
                }
                sum = num + sum;
            }

            int sum2 = sum % 10;
            if (sum2 > 0) {
                sum2 = 10 - sum2;
            }
            int chk2 = Character.getNumericValue(chk);
            System.out.println("The check digit should be: " + sum2);
            System.out.println("The check digit is: " + chk);
            if ( sum2 == chk2) {
                System.out.println("Number is valid.");
            }
            else {
                System.out.println("Number is not valid. ");
            }

            System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
            nums = input.nextLine();
        }

        System.out.println("Goodbye!"); 
        input.close();
    }
}
T.E. :

You can include your code that you only want done if the length ==16 in an if statement.

Meaning, instead of:

if (nums.length != 16) {
    //code if there is an error
}
//code if there is no error

you can do:

if (nums.length == 16) {
    //code if there is no error
} else {
    //code if there is an error
}

(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=421477&siteId=1