Reputation: 29
I have completed the program but in case of negative numbers it shows special character but I don't want that I want it should display number.
public class DigitAlphabetSpecialCharacter {
public static void main(String args[])
{
Scanner scanner=new Scanner(System.in);
char char1 =scanner.next().charAt(0);
if(char1>=48 && char1<=57)
{
System.out.print("char is Digit");
}
else if((char1>='a' && char1<='z')||(char1>='A' && char1<='Z'))
{
System.out.print("char is Alphabet");
}
else
{
System.out.print("char is special character");
}
}
} can anyone tell how to use negative numbers'ASCII value or an alternative suggestion?
Upvotes: 0
Views: 8330
Reputation: 51910
You are using a Scanner object, why not make use of its functionality.
Scanner scanner=new Scanner(System.in);
if (scanner.hasNextInt()) {
int value = scanner.nextInt();
System.out.print(value + " is a number");
return;
}
String value = scanner.next();
if (value.isEmpty()) {
return;
}
char c = value.charAt(0);
if ((c>='a' && c <= 'z') || (c>='A' && c <= 'Z')) {
System.out.print("char is Alphabet");
} else {
System.out.print("char is special character");
}
scanner.close();
Upvotes: 1
Reputation: 1042
try like this using regex
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
String char1 = String.valueOf(scanner.next().charAt(0));
if(char1.matches("[0-9]") || char1.matches("-[0-9]"))
{
System.out.print("char is Digit");
}
else if(char1.matches("[a-zA-Z]"))
{
System.out.print("char is Alphabet");
}
else
{
System.out.print("char is special character");
}
}
Upvotes: 1
Reputation: 41
Character cannot hold a negative value as it requires two characters. And a char variable can store only single character.
And rather than using ASCII value, you can use function predefined in Character class.
Upvotes: 2
Reputation: 5157
As per comments, if you enter -9
, your code will only take -
. You can simply check for the negative sign
public static void main(String args[])
{
Scanner scanner=new Scanner(System.in);
char char1 =scanner.next().charAt(0);
if((char1>=48 && char1<=57) || char1 == 45)
{
System.out.print("char is Digit");
}
else if((char1>='a' && char1<='z')||(char1>='A' && char1<='Z'))
{
System.out.print("char is Alphabet");
}
else
{
System.out.print("char is special character");
}
}
Upvotes: 1