繁体   English   中英

Character.isDigit() 错误:找不到适合 isDigit(String) 的方法

[英]Character.isDigit() error: no suitable method found for isDigit(String)

Kepp 在使用 Character.isDigit() 时出现错误

我在别处查过它并在那里测试得很好,但我一直在这里遇到这个错误。

  Scanner scnr = new Scanner(System.in);
  boolean hasDigit;
  String passCode;

  hasDigit = false;
  passCode = scnr.next();

  hasDigit = Character.isDigit(passCode);

  if (hasDigit) {
     System.out.println("Has a digit.");
  }
  else {
     System.out.println("Has no digit.");
  }

根据扫描仪输入期望 true 或 false。 不断向我抛出这个错误:

CheckingPasscodes.java:12: error: no suitable method found for isDigit(String)
  hasDigit = Character.isDigit(passCode);
                      ^
method Character.isDigit(char) is not applicable
  (argument mismatch; String cannot be converted to char)
method Character.isDigit(int) is not applicable
  (argument mismatch; String cannot be converted to int)

Character.isDigit()方法将char作为输入 - 您试图将其传递给String

该错误描述了问题所在:

参数不匹配; 字符串不能转换为字符

Scanner.next 方法将从输入 stream 返回整个标记(通常是单词)。 这些词是字符串。 Character.isDigit function 需要一个字符作为输入,而不是字符串。

您可以遍历单词,将每个字母作为 char 并测试它们:

for (int i = 0; i < passCode.length(); i++){
    char c = passCode.charAt(i);
    if (Character.isDigit(c)) {
        hasDigit = true;
    }
}

错误是hasDigit = Character.isDigit(passCode); Character.isDigit()需要一个字符作为参数,但您传递的是字符串。 所以更正这将字符串转换为字符。 你可以试试

     Scanner scnr = new Scanner(System.in);
  boolean hasDigit;
  char passCode;

  hasDigit = false;
  passCode =  scnr.next().charAt(0);

  hasDigit = Character.isDigit(passCode);

  if (hasDigit) {
     System.out.println("Has a digit.");
  }

  else {
     System.out.println("Has no digit.");
  }

我发现这对我有用。 我使用 charAt() 将字符串中的每个指定索引设置为一个字符值。 从那里我创建了一个 if 语句,如果任何 char 变量有一个数字,它将 hasDigit 设置为 true,使用 Character.isDigit() enter image description here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM