java - 数组长度不同,Junit 中预期长度 = 1 实际长度 = 0

标签 java arrays string junit

Write a method that will search an array of strings for all strings that contain another string, ignoring capitalization. Then return an array of the found strings.

The method takes two parameters, the query string and the array of strings to search, and returns an array.

If the string isn't contained in any of the strings in the array, the method returns an array containing a single string: "Empty".

Example: If the string to search for is "me", and the array to search is ["home", "milk", "Mercury", "fish"], the method should return ["home", "Mercury"].

这是我的解决方案,它在 Eclipse 中有效,但在游戏中它们显示错误消息:

array lengths differed, expected.length=1 actual.length=0

代码:

static String[] findWord(String x, String[] y){
     
     ArrayList<String> arrList = new ArrayList<String>();
      
      for(String s: y){
            if(s.toLowerCase().contains(x.toLowerCase()))
            arrList.add(s);
      }
    String[] arr = arrList.toArray(new String[arrList.size()]);

    if(!arrList.isEmpty())
    return arr;
      
    else
      return new String[0]; 
      
      }

我不知道这意味着什么,我尝试在 Google 上找到它,但找不到对我有用的东西。

最佳答案

array lengths differed, expected.length=1 actual.length=0

这意味着,当正确的返回值为长度为 1 的数组时,您将返回长度为 0 的数组。预期长度为 1,实际长度> 返回的是 0。

什么时候返回长度为0的数组?它一定是函数的最后一行出了问题,因为这是唯一返回空数组的地方。

您的代码不符合此条件:

If the string isn't contained in any of the strings in the array, the method returns an array containing a single string: "Empty".

当没有匹配项时,您将返回new String[0]。您需要返回一个包含字符串“Empty”的 1 元素数组。

关于java - 数组长度不同,Junit 中预期长度 = 1 实际长度 = 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30202810/

相关文章:

java - JBox2d 中有 RopeJoint 吗?

php - 如何对多维数组中的特定键进行求和和计数

c - 如何在 C 中正确清空字符串(字符数组)?

java - Android (Java) 转换 hh :mm:ss time String into a number representation

php - 使用 mysql_fetch_assoc 获取数组

Java 8 字符串比较

java - 找不到 ColdFusion 组件或接口(interface) javaloader.JavaLoader

java - 为什么在长时间运行的应用程序中出现 SocketException?

java - Quartz 中的嵌套作业

c++ - 模板结构作为数组