sukiyo
sukiyo

Reputation: 145

How to control how many letters and numbers the user enters into an input prompt?

I'm new to programming and we were given our first assignment! My whole code is working fine, but here is my problem:

We have to prompt the user to enter in an account ID that consists of 2 letters followed by 3 digits.

So far I only have a basic input/output prompt

//variables

String myID;

//inputs

System.out.println("Enter your ID:");
myID = input.nextLine();

So all it does is let the user enter in how many letters and digits they want, in any order and length. I don't understand how to "control" the user's input even more.

Upvotes: 2

Views: 146

Answers (1)

mc20
mc20

Reputation: 1175

As you said you are not aware of regex ,I have written this code to iterate by while loop and check if each character is a alphabet or digit. User is prompted to provide account number till the valid one is entered

import java.util.Scanner;

class LinearArray{

    public static void main(String args[]){

        Scanner input = new Scanner(System.in);
        boolean isIdValid = false;
        String myId;

        do{
            System.out.println("account ID that consists of 2 letters followed by 3 digits");           
            myId = input.nextLine();
            //Check if the length is 5
            if (myId.length() == 5) {
                //Check first two letters are character and next three are digits
                if(Character.isAlphabetic(myId.charAt(0))
                && Character.isAlphabetic(myId.charAt(1))
                && Character.isDigit(myId.charAt(2))
                && Character.isDigit(myId.charAt(3))
                && Character.isDigit(myId.charAt(4))) {
                    isIdValid = true;
                }
             }
           }while(!isIdValid);
        }       
    }

Upvotes: 1

Related Questions