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

标签 java arrays

我很确定我已经正确完成了大部分代码,但我返回了错误的东西?我尝试过使用 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/

相关文章:

java - 如何将基于 Actor 的源与 Akka Graph 结合使用?

java - 使用 WriteTimeoutHandler 在 Netty 中实现保活消息

java - 已经安装了德语 Babel。在 Eclipse 中运行的应用程序现在是德语,但导出为 "Eclipse product"仍然是英语

javascript - 在javascript中使用给定字符串的值获取多维数组的索引

c# - 如何以及何时放弃在 C# 中使用数组?

java - 如何禁用 eclipse/java 中记录器字段的未使用字段值警告

java - 如何重绘 - 在处理中重新启动循环

javascript - 我可以用 JS 数组做到这一点吗?

python:可变长度2矩阵的平均值

java - For(each) 循环两次填充组合框