mama
mama

Reputation: 9

How would i do input validation?

Tells the user if the number entered is even or even. I need help with the input validation. The validation i need do is that the user cannot entered anything but a number. Trying to do the validation without the try and catch method.

import java.util.Scanner;
  public class oddoreven {
      public static void main (String [] args) {
         Scanner input = new Scanner (System.in);

         //declaractions
         int num; 

         //while loop
         do{ 
         System.out.println("PLease enter a number to see whether it is even or odd. To end tyype in -99.");
         num = input.nextInt();  

         // input valid


        }while(num != -99);  // loop ends

 // begins the method
      public static void is_odd_or_even_number(int number){   
         int rem = number%2;


      \

Upvotes: 0

Views: 53

Answers (3)

jack jay
jack jay

Reputation: 2503

You can use regex to check whether all the characters of string entered by user are digits or not,

 num.matches("[0-9]+") // return true if all characters are digits

or

 num.matches("^[0-9]*$") // return true if all characters are digits

but before that change your num = input.nextint() to num = nextLine() and make num as String. if you dont do this there is no need of validating user input as you are requiring.

Upvotes: 0

Andrew Jenkins
Andrew Jenkins

Reputation: 1609

You can use Scanner.nextLine() to get a string input. Then loop through the characters to make sure they are all digits. (assuming non-negative integers only)

string rawInput = input.nextLine();
boolean validInput = true;
for (char c : rawInput) {
      if (!Character.isDigit(c)) {
           validInput = false;
           break;
      }
}

if (validInput) {
    int num == Integer.parseInt(rawInput);
    // proceed as normal
}
else {
    // invalid input, print out error message
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201419

You can call Scanner.hasNextInt() to determine if the next input is an int (and consume anything else). Also, you might make an infinite loop and break when the input is -99 (or 99, your code tests for 99 but your prompt says -99). Finally, you should call your method. Something like,

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int num;
    do {
        System.out.println("Please enter a number to see whether it is "
                + "even or odd. To end type in -99.");
        if (input.hasNextInt()) {
            num = input.nextInt();
            if (num != -99) { // <-- directions say -99.
                is_odd_or_even_number(num);
            } else {
                break;
            }
        } else {
            System.out.printf("%s is not a valid int.%n", input.nextLine());
        }
    } while (true);
}

Upvotes: 1

Related Questions