但是当我尝试返回数组时,它给了我一个奇怪的引用,这是返回的:数组是:[I @ 895684 我不知道为什么它不起作用,我也不确定如何包括数组大小的子列表a [1],a [2],a [3] ... a [n-1]
import java.util.*;
class SumArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some numbers (all on one line, separated by commas):");
String line = input.nextLine();
String[] numbers = line.split(",");
int[] array = new int[numbers.length];
for(int i=0; i<array.length; i++)
array[i]=Integer.parseInt(numbers[i].trim());
int[] highSum = highestSum(array);
System.out.println("The array is: "+highSum);
}
public static int[] highestSum(int[] a)
{
// int[] array = new int[a.length];
//int end = a.length - 1;
int sum = 0;
int[] highestSum = new int[a.length-1];
for (int j=0; j<a.length - 1; j++) {
for(int i=0; i<a.length; i++){
sum = sum + a[i];
System.out.println(sum + " " + a.length);
}
highestSum[j] = sum;
System.out.println(highestSum[j]);
}
return highestSum;
}
答案 0 :(得分:2)
此
int[] highSum = highestSum(array);
System.out.println("The array is: "+highSum);
将打印您看到的结果。使用
System.out.println("The array is: " + Arrays.toString(highSum));
打印内容。
答案 1 :(得分:0)
我已根据您的要求修改了逻辑。这会将最大总和子列表附加到单个数组中并打印出来。
要打印数组,您可以使用Arrays.toString(highSum)
对于两个数组的连接,您可以参考以下public static int[] concatArray(int[] A, int[] B)
注意:这是蛮力的方式。您可以研究解决问题的更优化方法;)。
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out
.println("Enter some numbers (all on one line, separated by commas):");
String line = input.nextLine();
String[] numbers = line.split(",");
int[] array = new int[numbers.length];
for (int i = 0; i < array.length; i++)
array[i] = Integer.parseInt(numbers[i].trim());
int[] highSum = concatArray(array, highestSum(array));
System.out.println("The array is: " + Arrays.toString(highSum));
}
public static int[] highestSum(int[] a)
{
// int[] array = new int[a.length];
// int end = a.length - 1;
int result[]=new int[0];
for (int k = a.length-2; k >=0 ; k--)
{
int[] highestSum = new int[0];
int maxSum= Integer.MIN_VALUE;
for (int j = 0; j < a.length; j++)
{
int sum = 0;
int [] tempSum = new int[k+1];
int index = 0;
if(j+k<a.length)
{
for (int i = j; i <= j+k ; i++)
{
sum = sum + a[i];
tempSum[index++]= a[i];
}
if(sum > maxSum)
{
maxSum = sum;
highestSum = tempSum;
}
}
}
result = concatArray(result, highestSum);
}
return result;
}
public static int[] concatArray(int[] A, int[] B)
{
int aLen = A.length;
int bLen = B.length;
int[] C= new int[aLen+bLen];
System.arraycopy(A, 0, C, 0, aLen);
System.arraycopy(B, 0, C, aLen, bLen);
return C;
}