vendredi 28 octobre 2016

Can someone tell me how to properly validate whether a character is a specific letter or not?

So i'm trying to write a test program that will tell me whether or not a sequence of numbers is a magic square. However, I'm i'm trying to figure out how to correctly validate the user input. In short, I want to prompt users for an integer and continue doing so until they enter the letter 'x'. If they accidentally enter a letter instead of x before they are done, I want the program to give them a brief error before allowing the continuation of their input until x is entered. Here's what I have right now:

 import java.util.*;
public class TestSquare
{
   public static void main(String [] args)
   {
      Square numbers = new Square();

      Scanner in = new Scanner(System.in);
      System.out.println("Enter an integer(x to exit): ");
      int i = in.nextInt();
      char c = (char)(i + '0');

      while(Character.isDigit(c))
      {
         numbers.add(i);
         System.out.println("Enter an integer(x to exit): ");
         i = in.nextInt();
         c = (char)(i + '0');
      }
      if( c == 'x')
      {
         numbers.isSquare();
         numbers.isUnique();
         numbers.isMagic();
      }
      else
      {
         System.out.println("***Invalid Data Entry. Please Try Again or enter x to exit.***");
         i = in.nextInt();
         c = (char)(i + '0');
      }
   }
}

This lets me input integers just fine continuously, but the moment I input a letter (including x) the program runs into an error and stops. Can someone tell me how to properly validate this please? Thank you!

Aucun commentaire:

Enregistrer un commentaire