Java流提供“不可比较的类型:int和String”,即使在int转换为String之后
我有一个Java类,它将0和给定数字之间的所有数字平方。然后使用字符串将每个平方数转换为字符串。价值(数字)。给定的数字也会转换为字符串。然后,平方数和给定的数字(都转换为字符串)被传递到一个函数中,该函数应该使用流计算该数字作为字符串出现在平方数中的次数。然而,当进行这种比较时,Java给了我一个错误:
incomparable types: int and String
int count = squareString.chars().filter(ch -> ch == criticalDigit).count();
当整数已经被转换成字符串时,为什么这个流给了我这个错误?我怎样才能成功地计算一个字符串数字在字符串整数中出现的次数
我目前拥有的代码是:
import java.util.stream.*;
public class CountDig {
public static int nbDig(int n, int d) {
int[] squaredNumbers = new int[n];
int number = 0;
String strV = String.valueOf(d);
int totalCount = 0;
for (int i = 0; i < n; i++) {
number = i * 2;
String squaredString = String.valueOf(number);
totalCount += occurrenceChecker(squaredString, strV);
}
return totalCount;
}
public static int occurrenceChecker(String squareString, String criticalDigit) {
int count = squareString.chars().filter(ch -> ch == criticalDigit).count();
return count;
}
}
# 1 楼答案
首先,您试图从返回类型为
String
的函数返回int
(count
):公共静态字符串发生检测器(字符串squareString、字符串criticalDigit)
第二条:
criticalDigit
是String
,而ch
是int
。(^{另一种方法是使用^{} 函数来计算给定
String
的值:这是假设您想要返回结果的
String
表示# 2 楼答案
chars()返回IntStream,因此ch在Lambda表达式中是整数
如果方法nbDig上的d在“0”到“9”之间,下面的代码将起作用
如果不是,你应该改变算法
如果d可以是多个数字,则为ok。下面的代码帮助你