0% found this document useful (0 votes)
43 views2 pages

Scanner Scanner (System.) System. .Println ( (.Hasnextint ) ( .Nextint ) (System. .Println .Next ) ) (! )

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.

Uploaded by

aasxdas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views2 pages

Scanner Scanner (System.) System. .Println ( (.Hasnextint ) ( .Nextint ) (System. .Println .Next ) ) (! )

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.

Uploaded by

aasxdas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

To validate Only integers be entered

Scanner sc= new Scanner(System.in);


// 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);

You might also like