gpt4 book ai didi

即使在 int 转换为 String 之后,Java 流也会给出 'incomparable types: int and String'

转载 作者:行者123 更新时间:2023-11-30 02:01:52 25 4
gpt4 key购买 nike

我有一个 Java 类,用于对 0 和给定数字之间的所有数字进行平方。然后使用 String.valueOf(number) 将每个平方数转换为字符串。给定的数字也会转换为字符串。然后,将平方数和给定的数字(均转换为字符串)传递到一个函数,该函数应该使用流来计算该数字在平方数中作为字符串出现的次数。然而,当进行这种比较时,Java 给出了错误:

incomparable types: int and String
int count = squareString.chars().filter(ch -> ch == criticalDigit).count();

当整数已经转换为字符串时,为什么这个流给我这个错误?如何成功计算字符串数字在字符串 int 中出现的次数?

我目前拥有的代码是:

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;
}

}

最佳答案

chars() 返回 IntStream 因此 ch 是 Lambda 表达式中的整数

如果方法 nbDig 上的 d 位于“0”到“9”之间,则以下代码有效。

squareString.chars().filter(ch -> ch == criticalDigit.charAt(0)).count()

如果不是,你应该改变算法。

<小时/>

ok 如果 d 可以是多位数字。下面的代码可以帮助你。

squareString.chars().filter(ch -> criticalDigit.indexOf(ch) != -1).count()

关于即使在 int 转换为 String 之后,Java 流也会给出 'incomparable types: int and String',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52573347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com