Java将INT数组中的项添加到String数组中

时间:2014-10-28 21:19:20

标签: java arrays string 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;

    }

-

-

结果数组包含INTEGERS项,returnValue是字符串。

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

2 个答案:

答案 0 :(得分:1)

要将数组转换为String,您可以使用java.util.Arrays.toString

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

答案 1 :(得分:1)

我假设您正在尝试返回包含您找到的所有斐波那契数字的字符串? 如果是,请更改以下内容:

StringBuilder returnValue = new new StringBuilder()

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

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

将返回值更改为:

return returnValue.toString();

这应该解决它(最后加上',')