-1

I am working on an assignment right now where I have to enter an input in "ABC123456" format entry and see if it is valid or not. I don't understand how to check each character if it is a number or letter. Here is what I have so far:

import java.util.Scanner;
public class NetID {


    public static void main(String[] args) {    
        Scanner input = new Scanner (System.in);
        String userInput, char0thru2, char3thru8, uppercase, netID;

        System.out.println("Please enter the NetID to verify:");
        userInput = input.nextLine();

        if (userInput.length() != 9) {
            System.out.println("Your NetID needs to be 9 characters long, it needs to be in this format: ABC123456");
        }   
        if (userInput.length() == 9){
            char0thru2 = userInput.substring(0, 3);
            char3thru8 = userInput.substring(3, 9);
            uppercase = char0thru2.toUpperCase();
        }
    }
}
Pierre Anken
  • 308
  • 2
  • 16
  • 3
    https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isLetter-char-, https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isDigit-char- – JB Nizet Oct 22 '17 at 10:56
  • 2
    https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html – M. le Rutte Oct 22 '17 at 10:56

3 Answers3

1

Just use a pattern:

String userInput = "ABC133456";

    if(!Pattern.matches("[A-Z]{3}[0-9]{6}", userInput))
         System.out.println("Your NetID needs to be 9 characters long, it needs to be in this format: ABC123456");
    else
         System.out.println("Ok!");
Pierre Anken
  • 308
  • 2
  • 16
0

You can try this way

Loop over the input string, and get each character at the counter position of the loop , then compare the ASCCI values of each character. If u want first 3 character as letters then till the counter is 2 compare them with ASCCI value of A-Z and all other with ASCCI value of 0-9

You can try below code , may have some compilation errors as I haven't compiled it :(

  if(userInput.length==9)
   {
     for (int i =0;i<userInput.lenght;i ++){
       if (i <3){
        if(!(userInput.charAt(i)<91      &&userInput.charAt(i)>64)){
         System.out.println("invalid string");
          break;
        }
      }
      if (i >2){
      if(!(userInput.charAt(i)<58 &&userInput.charAt(i)>47)){
       System.out.println("invalid string");
        break;
      }
     }
    }
   }
Nutan
  • 778
  • 1
  • 8
  • 18
0

Simply iterate over String and use isDigit() of Character class,sample code below, hope it helps:

String inp="qwerty43";
for(int i=0;i< myStr.length();i++){
       if (Character.isDigit(myStr.charAt(i))) {
            System.out.println("Digit Found");
        } else {
            System.out.println("Letter Found");
        }
}