程序显示值是否为字母然后打印 "Alphabet" 如果它是数字则打印 "Digit" 而对于其他字符打印 "Special Character"?

program to show if the value is alphabet then print "Alphabet" if it’s a number then print "Digit" and for other characters print "Special Character"?

我已经完成了程序,但如果是负数,它会显示特殊字符,但我不希望它显示数字。

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

    }
}

} 谁能告诉我如何使用负数的 ASCII 值或其他建议?

根据评论,如果您输入 -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");

        }
    }

字符不能包含负值,因为它需要两个字符。而一个char变量只能存储单个字符。

您可以使用 字符 class.

中预定义的函数,而不是使用 ASCII 值

尝试使用正则表达式

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

      }
    }

您正在使用 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();