有 Java 编程相关的问题?

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

Java将项目从INT数组添加到字符串数组

public static String fibonacci(int a, int b){

        int max = 10;
        String returnValue;

        int[] result = new int[max];
        result[0] = a;
        result[1] = b;
                for (int i1 = 2; i1 < max; i1++) {
                    result[i1] = result[i1 - 1] + result[i1 - 2];
                }
                for (int i3 = 0; i3 < max; i3++) {
                    //Here you can do something with all the values in the array one by one
                    //Maybe make something like this?:
                    int TheINTthatHasToBeAdded = result[i3];
                    //The line where TheINTthatHasToBeAdded gets added to the String returnValue

                }           


        return returnValue;

    }

-

-

结果数组的项是整数,返回值是字符串

我的问题是,;如何将结果数组中的项添加到returnValue数组中


共 (2) 个答案

  1. # 1 楼答案

    我想你是想返回一个字符串,其中包含你找到的所有fibonaci数字? 如果是,请更改以下内容:

    StringBuilder returnValue = new new StringBuilder()
    

    将以下内容添加到第二个循环中

    returnValue.append(result[i3]).append(",");
    

    将返回值更改为:

    return returnValue.toString();
    

    这应该可以解决这个问题(最后加上一个“,”

  2. # 2 楼答案

    要将数组转换为String,可以使用^{}

    returnValue = java.util.Arrays.toString(result);
    

    尽管如此,返回计算数组的String表示仍然不是一个好的设计。最好返回int[],让客户端将其转换为String或以其他方式使用它或向用户显示它

    以下是该方法的外观:

    //changed the return type from String to int[]
    public static int[] fibonacci(int a, int b) {
        int max = 10;
        int[] result = new int[max];
        result[0] = a;
        result[1] = b;
        for (int i1 = 2; i1 < max; i1++) {
            result[i1] = result[i1 - 1] + result[i1 - 2];
        }
        return result;
    }
    
    //in client method, like main
    public static void main(String[] args) {
        //store the result of fibonacci method in a variable
        int[] fibonacciResult = fibonacci(0, 1);
        //print the contents of the variable using Arrays#toString
        System.out.println("Fibonacci result:" + Arrays.toString(fibonacciResult));
    }
    

    或者甚至使用另一种方式来消耗结果。下面是另一个例子:

    public static void main(String[] args) {
        //store the result of fibonacci method in a variable
        int[] fibonacciResult = fibonacci(0, 1);
        //print the contents of the variable using Arrays#toString
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < fibonacciResult.length; i++) {
            sb.append(fibonacciResult[i])
                .append(' ');
        }
        System.out.println("Fibonacci result:" + sb.toString());
    }