![](/img/trans.png)
[英]The java method Character.isDigit(char) returns true with an input of 'O'
[英]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.