gpt4 book ai didi

java - 如何在单个数组中返回重复三次的数组?

转载 作者:行者123 更新时间:2023-12-01 19:29:09 24 4
gpt4 key购买 nike

我很确定我已经正确完成了大部分代码,但我返回了错误的东西?我尝试过使用 copyOf() 但仍然遇到同样的问题。看起来我正在返回数组的对象而不是元素?我需要 treble 方法返回按顺序重复的原始数组,在一个数组中重复三次。因此,三倍时 [1,2,3,] 应该看起来像 [1,2,3,1,2,3,1,2,3] 。任何帮助将非常感激。

import java.util.Scanner;
import java.util.Arrays;
public class ArrayExercises
{
public static void main(String[] args)
{
final int SIZE = 5;
int[] array = new int[SIZE];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < array.length; i++)
{
System.out.print("Please enter whole number " + (i + 1) + ": ");
int input = scanner.nextInt(); // get input from the user
array[i] = input; // store the value in the array
}
printArray("Input array:", array);
// call method sum and print out the result
int sum = sum(array);
System.out.println("The sum of elements is " + sum);
// call method repeat and print out the result
int[] trebled = repeat(array);
System.out.println("The repeated array is " + trebled);
}
public static void printArray(String msg, int[] array)
{
System.out.println(msg + " " + Arrays.toString(array));
}
public static int sum(int[] array)
{
int s = 0;
for (int i = 0; i < array.length; i++)
s += array[i];
return s;
}
public static int[] repeat(int[] array) //this is the part I'm having trouble with
{
int len = array.length;
int[] multiplied = new int[len*3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < len; j++)
{
multiplied[i * len + j] = array[j];
}
}
return multiplied;}
}

最佳答案

尝试使用:

System.out.println("The repeated array is "  + Arrays.toString(trebled)); 

打印数组而不是使用数组变量名称打印,否则将打印数组的地址而不是内容。

关于java - 如何在单个数组中返回重复三次的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60324347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com