-2
static void a1()
{

   int choice;
   Scanner sc1 = new Scanner(System.in);
   System.out.println();
   System.out.print("Enter Part#: ");
   pa[count] = sc1.nextLine();

   System.out.println();
   System.out.print("Enter Make: ");
   ma[count] = sc1.nextLine();

   System.out.println();
   System.out.print("Enter description: ");
   so[count] = sc1.nextLine();

   System.out.println();
   System.out.print("Enter price: ");
   pr[count] = sc1.nextLine();

   ++count; 

 } 

How do I get the user to input either only numbers or letters from A-Z?

Tunaki
  • 132,869
  • 46
  • 340
  • 423

2 Answers2

0

Wrap each section in a while loop. That repeats asking the user for input until they enter valid information.

do
{
    System.out.print("Enter Part#: ");
    pa[count] = sc1.nextLine();
}
while(checkAlpha(pa[count]) == false);

Then create a function to check each value in the string for valid characters.

public static boolean checkAlpha(String phrase)
{
    char[] tempChars = phrase.toCharArray();
    for(char c : tempChars)
    {
        if(!Character.isLetterOrDigit(c))
        {
            return false;
        }
    }
    return true;
}

You also could do this using regex by changing the while check to:

while(!pa[count].matches("^[a-zA-Z0-9]+$"));
duncan
  • 1,161
  • 8
  • 14
0

If you use the Pattern class to build a Matcher, you should be able to just use the pattern [^\\p{Alnum}] and then call the find() method to look for any matching instance of the pattern.

ZGski
  • 2,398
  • 1
  • 21
  • 34