[英]Java adding items from an INT array to a String array
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數組?
要將數組轉換為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());
}
我假設您正在嘗試返回包含找到的所有斐波那契數字的字符串? 如果是這樣,請更改以下內容:
StringBuilder returnValue = new new StringBuilder()
將以下內容添加到第二個循環中
returnValue.append(result[i3]).append(",");
將返回值更改為:
return returnValue.toString();
這應該可以解決(最后有一個額外的“,”)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.