Ramos801 2021-12-17 03:40 采纳率: 85.7%
浏览 26
已结题

一个关于java array的问题

翻到好久之前一个问题,然后咋做都不会了
part1

public static int[] getIndices(String[] sa, String s) {

    int[] result = null;
    int f = 0 ;
    int count =0;
    for (int i= 0;i < sa.length;i ++ ) {
           
        if (sa[i].equals(s)) {
       f=i;
         count ++;
              
   

                    }
       
                       result = new int [count];
       for(int j =0;j<count;j++) {    
                          
           result[j]=f;
           
       }

        }
 
 
        
        
    
    

    return result;
}

}

part2:@Test
public void test_getIndices_01() {
String[] input = {"d", "c", "a", "b", "c", "d", "a", "a", "d", "a"};
int[] result = Utilities.getIndices(input, "a");
int[] expected = {2, 6, 7, 9};
assertArrayEquals(expected, result);
}
@Test
public void test_getIndices_02() {
String[] input = {"d", "c", "a", "b", "c", "d", "a", "a", "d", "a"};
int[] result = Utilities.getIndices(input, "b");
int[] expected = {3};
assertArrayEquals(expected, result);
}

@Test
public void test_getIndices_03() {
    String[] input = {"d", "c", "a", "b", "c", "d", "a", "a", "d", "a"};
    int[] result = Utilities.getIndices(input, "e");
    int[] expected = {};
    assertArrayEquals(expected, result);
}

}

给出一个String []然后里面有几个字母;再输入一个string,若输入的string和String[]里的元素相同则输出result[] result的元素就是string在 String[] 所在的位置;
以上代码的part1 是我写的 part2 是junittest, 运行之后result里的元素只有string在String[] 最后出现的位置。
望大家可以找出问题并解答
不胜感激

  • 写回答

1条回答 默认 最新

  • 关注

    因为你f变量只能保存一个值,前面循环结束后 f 中就只是最后一次赋值的值。
    需要把f也改成数组才能保存每一个值
    并且 result = new int [count];创建数组不要在循环中重复创建,要在循环外创建。
    之后把f数组中元素复制到result数组中即可。

    你题目的解答代码如下:

    public static int[] getIndices(String[] sa, String s) {
     
        int[] result = null;
        int[] f = new int[sa.length];
        int count = 0;
        for (int i= 0;i < sa.length;i++ ) {
            if (sa[i].equals(s)) {
               f[count] = i;
                count ++;
            }
        }
        result = new int [count];
        for(int j =0;j<count;j++) {    
            result[j]=f[j];
        }
        return result;
    }
    

    如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 12月25日
  • 已采纳回答 12月17日
  • 创建了问题 12月17日

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题