我已经完成了该计划,但如果是负数,则会显示特殊字符,但我不想要它,我希望它应该显示数字。
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");
}
}
} 任何人都可以告诉如何使用负数&#39; ASCII值或替代建议?
答案 0 :(得分:1)
字符不能保持负值,因为它需要两个字符。 char变量只能存储单个字符。
而不是使用ASCII值,您可以使用 Character 类中预定义的函数。
答案 1 :(得分:0)
根据评论,如果您输入-9
,则您的代码只会-
。您只需检查负号
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");
}
}
答案 2 :(得分:0)
尝试使用正则表达式
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");
}
}
答案 3 :(得分:0)
您正在使用Scanner对象,为什么不使用它的功能。
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();