Ok guys so i'm using this string function "charAT" to store charater variable to store in char r. But we know user can input anything. When user enters a numeric value like 123 or 5 or anything charAt is storing that in char variable r. Exception should have come but it didn't. How is char variable able to hold a numeric value. How can i fix this? i want "r" to hold only char values and want the exception to occur if user inputs the numeric value.
package string;
import java.util.Scanner;
public class Example
{
Scanner s1;
String str;
char r;
Example()
{
s1 = new Scanner(System.in);
}
void display()
{
while(true)
{
try {
System.out.println("Please enter the grade");
str = s1.nextLine();
r = str.charAt(0);
System.out.println("The grade is "+ r);
break;
}
catch(Exception e)
{
System.out.println("you have entered an invalid input. Please try again \n");
}
}
}
public static void main(String[] args)
{
new Example().display();
}
}
In Java the value of String
and char
can also accept numeric values. So if you enter 123 as input then the String will be "123" and the char will be 1
. If you only want to get alphabets as input then you can do it using the hasNext
method in the Scanner
class of Java. This will use a Regular Expression
such as [A-Za-z]
to make sure only alphabets can be given as input.
while(true)
{
try
{
System.out.println("Please enter the grade");
while (!s1.hasNext("[A-Za-z]+")) {
System.out.println("you have entered an invalid input. Please try again \n");
s1.next();
}
str = s1.next();
r = str.charAt(0);
System.out.println("The grade is "+ r);
break;
}
catch (Exception e)
{
System.out.println("There was an exception \n");
}
}