Haider Abdullah Haider Abdullah - 14 days ago 8
Java Question

Number validation inside Do While loop and if statements

package validation;
import java.util.*;
public class Validation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String regex = "^[a-zA-Z ]+$";
String regex1 = "\\d[0123456789]";
String Char;
String Num;
do {
System.out.print("What Is Your Name:");
Char = input.nextLine();

if (Char.matches(regex))
System.out.println("Welcome"+" "+Char);
else if (Char.isEmpty())
System.out.println("String field should not be Empty.");
else if(!Char.matches(regex))
System.out.println("Please Enter A Valid String!");
} while(!Char.matches(regex));
do {
System.out.println("How Old Are you:");
Num = input.nextLine();
if (Num.matches(regex1))
System.out.println("You Are"+" "+Num);
else if (Num.isEmpty())
System.out.println("Number field should not be Empty.");
else if(!Num.matches(regex1))
System.out.println("Please Enter A Valid Number!");
} while(!Num.matches(regex1));
}
}


What are you seeing right now above is a working code and I don't have problem with it. The thing that I want to ask is that what if I want to add another feature on my code, like once you've type number 18 below on the number input field it will give you this output:

"Your are uderage".

Answer

First of all instead of storing age in String you should store it in int. Second variable names should always start with the lowercase. It should be num instead of Num.

If you want to do it like you have done it in your code then you can do like this.

do {

         System.out.println("How Old Are you:");
         Num = input.nextLine();
         if(Integer.parseInt(NUM)<18){
            System.out.println("Underage, exiting");
            break;
        }
        if (Num.matches(regex1))
            System.out.println("You Are"+" "+Num);
        else if (Num.isEmpty())
            System.out.println("Number field should not be Empty.");

        else if(!Num.matches(regex1))
            System.out.println("Please Enter A Valid Number!");

    }while(!Num.matches(regex1));  

Code conventions java : Code conventions