// Using isLetterOrDigit() to check whether user_id or any string entered by user has a digit and/or letter and no other symbols or characters. import java.util.Scanner; class test { public static void main(String ar[]) { Scanner sc=new Scanner(System.in); boolean flag =false; // keep the switch/flag off in the beginning. System.out.println("Enter user_id:"); String user_id = sc.nextLine(); // extract each character from user_id by charAt() method. for(int i=0;i<user_id.length();i++) { char ch = user_id.charAt(i); // get the 0th character, 1st character and so on.. // if ch is a letter and/or digit, its valid for user_id. If not, its invalid. if(! Character.isLetterOrDigit(ch)) // using ! to check the invlaid condition. { flag=true; // if any special symbol is found, set flag to true. System.out.println("USER ID CAN ONLY CONTAIN LETTERS AND DIGITS.. ");// no need to check rest of characters now. so break the loop. break; } } if(flag==false) {// if flag was still holding old value (false), then the user_id is valid. System.out.println("VALID USER ID!!"); } } } /* OUTPUT Enter user_id: user_1 USER ID CAN ONLY CONTAIN LETTERS AND DIGITS.. Enter user_id: user@123 USER ID CAN ONLY CONTAIN LETTERS AND DIGITS.. Enter user_id: user1 VALID USER ID!! */