0 Bewertungen0% fanden dieses Dokument nützlich (0 Abstimmungen)
7 Ansichten2 Seiten
The document describes how to validate user input in Java to ensure only integers or alphabets are entered. For integers, it uses a do-while loop to get input from the scanner and check if it is an integer with hasNextInt(). For alphabets, it uses while and do-while loops to get input and check if it matches the regular expression for a-z or A-Z with matches(), repeating the input prompt if invalid until a match is found.
The document describes how to validate user input in Java to ensure only integers or alphabets are entered. For integers, it uses a do-while loop to get input from the scanner and check if it is an integer with hasNextInt(). For alphabets, it uses while and do-while loops to get input and check if it matches the regular expression for a-z or A-Z with matches(), repeating the input prompt if invalid until a match is found.
The document describes how to validate user input in Java to ensure only integers or alphabets are entered. For integers, it uses a do-while loop to get input from the scanner and check if it is an integer with hasNextInt(). For alphabets, it uses while and do-while loops to get input and check if it matches the regular expression for a-z or A-Z with matches(), repeating the input prompt if invalid until a match is found.
// scan the array System.out.println("plz enter values"); do { if (sc.hasNextInt()) { number = sc.nextInt(); isNumber=true; } else { System.out.println("mistake"); isNumber=false; sc.next(); } } while (!(isNumber));
To validate Only alphabets be entered
a. Using while loop Scanner sc= new Scanner(System.in); // scan the array name=sc.nextLine(); while(!name.matches("[a-zA-Z]")) { System.out.print("retype") ; name=sc.nextLine(); }
b. Using Do while loop
do
{ System.out.print("Enter String"); name=sc.nextLine(); if (name.matches("[a-zA-Z]+")) { name = sc.nextLine(); match=true; } else { System.out.print("retype") ; match=false; } }while(!match);