用Java在一个数列里找出等于一个数的两个数

问题遇到的现象和发生背景
public String getPairSumTo(int[] addends, int targetSum) {
        // TODO: write statements here
        int indexone;
        int j;
        String output = "0";
        if(addends.length<2){
            output = "0";
        } else {
            for (indexone = 0; indexone < addends.length; indexone++) {
                for (j = indexone + 1; j < addends.length; j++) {
                    if (addends[indexone] + addends[j] == targetSum) {
                        output = indexone + ", " + j;
                    } else{
                        output = "0";
                    }
                }
            }
        }return output;
    }

我想要达到的结果

已经尽力了,还是求不出来。
要求
getPairSumTo(new int[] {1, 2, 3, 4, 5, 6}, 10)
最后会return
"4, 6"

双层for循环判断,你这个代码逻辑不对,代码修改如下:

public String getPairSumTo(int[] addends, int targetSum){
        String s="";
        for(int i=0;i<addends.length;i++){
            for(int j=i+1;j<addends.length;j++){
                if(addends[i]+ addends[j]== targetSum){
                    s = Integer.toString(addends[i]) + "," + Integer.toString(addends[j]);
                    return s;
                }
            }
        }
        return s;
    }

希望对您有所帮助,有用的话采纳一下吧


public class Main {
    public static void main(String[] args) {
        getPairSumTo(new int[]{1,2,3,4,5,6}, 6);
    }

    //输出数组数组中两个数值之和等于targetSum的数
    public static void getPairSumTo(int[] addends, int targetSum) {
        int indexone;
        int j;
        if(addends.length>2){
            //外层for循环之所以要indexone < addends.length - 1,是为了防止内层for循环j = indexone + 1造成数组越界
            for (indexone = 0; indexone < addends.length - 1; indexone++) {
                for (j = indexone + 1; j < addends.length; j++) {
                    if (addends[indexone] + addends[j] == targetSum) {
//每有一组符合要求的数据就输出,避免漏掉
                        System.out.println(addends[indexone] + ", " + addends[j]);
                    }
                }
            }
        }
    }
}


您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632