有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

}

共 (2) 个答案

  1. # 1 楼答案

    首先,您试图从返回类型为String的函数返回intcount):

    公共静态字符串发生检测器(字符串squareString、字符串criticalDigit)

    第二条:

      int count = squareString.chars().filter(ch -> ch == criticalDigit).count();
    

    criticalDigitString,而chint。(^{}返回“此序列中字符值的IntStream”)

    另一种方法是使用^{}函数来计算给定String的值:

    public static String occurrenceChecker(String squareString, String criticalDigit) {
      int temp = 0;
      int count = 0;
      while(squareString.indexOf(criticalDigit, temp) != -1) {
          count++;
          temp = squareString.indexOf(criticalDigit, temp) + criticalDigit.length();
      }
      return Integer.toString(count);
    } 
    

    这是假设您想要返回结果的String表示

  2. # 2 楼答案

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

    如果方法nbDig上的d在“0”到“9”之间,下面的代码将起作用

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

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


    如果d可以是多个数字,则为ok。下面的代码帮助你

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