我使用的代码应该识别某物是否是数字、字母等,并返回正确的响应。
我收到错误,无法在字符上使用 boolean 值,因此我将输入字符转换为字符串。
现在我正在使用下面的代码,但我无法在字符串上使用数学运算符。我需要使用 char 作为输入 b/c 程序应该能够识别字母和特殊字符。
我可以使用范围吗?即“1-9”和“a-z”?我已经尝试过多种身份([1-9]、“[1-9]”等),但我不断收到错误消息。我的猜测是我的格式不正确。
package charreader;
import java.util.Scanner;
import java.io.*;
public class Charreader {
public static void main(String[] args) throws IOException
{
Scanner newScan = new Scanner(System.in);
//prompt for input and read it
System.out.println("Enter a character.");
char ch = (char)System.in.read();
//convert ch to string
String st = String.valueOf(ch);
if (st >= 1 && <= 9 )
{
System.out.println("Digit");
}
else
{
System.out.println("Not a digit.");
}
我唯一要做的工作是:
if (st == '0')
{
System.out.println("Digit");
}
else
{
System.out.println("Not a digit.");
但我不想这样运行整个程序。这会很笨重,而且通常是不好的做法。
最佳答案
在 Java 中,我们有内置的方法。就像这些角色:
char a = 'b';
Character.isDigit(a);
Character.isLetter(a);
即使对于字符串,您也可以使用这些方法:
public static boolean isNumeric(String str) {
try {
int number = Integer.parseInt(str);
return true;
} catch (Exception e) {
return false;
}
}
编辑:如果您不想使用字符类,我们可以这样做:
char ch = 'r';
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
System.out.println("alphabetic");
else if(ch >= '0' && ch <= '9')
System.out.println("digit");
else
System.out.println("none");
关于java - 对范围使用 if/else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52796897/