将数组传递给另一个方法并复制它

时间:2016-10-21 16:34:48

标签: java arrays methods

我正在尝试将数组从一个方法传递到另一个方法,然后将该数组的内容复制到一个新数组中。我在完成该任务的语法方面遇到了麻烦。 有没有人有一些我可以阅读有关这个​​主题的参考资料,或者我可以申请一个有用的提示?

如果这是一个菜鸟问题我很抱歉,但我只是在兼职工作3-4周。

我知道Java使用pass by value,但是我迷失的地方是......我应该在将sourceArray复制到targetArray之前调用它吗?

我的目标不仅仅是给出答案,我需要明白为什么。

先谢谢...

package cit130mhmw08_laginess;

import java.util.Scanner;

public class CIT130MHMW08_Laginess 
{

public static void main(String[] args) 
{
    Scanner input = new Scanner(System.in);

    System.out.println("Please enter the total number of dealers: ");
    int numDealers = input.nextInt();
    numDealers = numberOfDealers(numDealers);

    System.out.printf("%nPlease enter the required data for each of your dealers:");
    dataCalculation(numDealers);

}//main

//METHOD 1
public static int numberOfDealers(int dealers)
{
    int results;

    Scanner input = new Scanner(System.in);

    while(dealers < 0 || dealers > 30)
    {
        System.out.printf("%nEnter a valid number of dealers: ");
        dealers = input.nextInt();  
    }
    results = dealers;
    return results;

}//number of dealers methods

//METHOD 2
public static void dataCalculation(int data)
{
    String[] dealerNames = new String[data];

    Scanner input = new Scanner(System.in);

    System.out.printf("%nEnter the names of the dealers:%n ");

        for(int i = 0; i < data; i++)
        {
            String names =input.nextLine();
            dealerNames[i]= names;
        }

    int[] dealerSales = new int[data];
    System.out.printf("%nEnter their sales totals: %n");

        for(int i = 0; i < data; i++)
        {
            int sales = input.nextInt();
            dealerSales[i] = sales;
        }


    for(int i = 0; i < data; i++)
    {
        System.out.println(" " + dealerNames[i]);
        System.out.println(" " + dealerSales[i]);
    }
    //gather the required input data. 
    //Perform the appropriate data validation here.

}//data calculations

//METHOD 3
public static int commission(int data)
{
    //Create array
    int[] commissionRate = new int[dealerSales]; 

    //Copy dealerSales array into commissionRate
    System.arraycopy(dealerSales, 0, commissionRate, 0, dealerSales.length);

    //calculate the commission array.
    //$1 - $5,000...8%
    //$5,001 to $15,000...15%
    //$15,001...20%

    //

}//commission method 
}//class

1 个答案:

答案 0 :(得分:1)

如果要复制数组,可以使用Arrays.copyOf(origin, length)方法。它需要2个参数,第一个是应该从中复制数据的数组,第二个是新数组的长度,并导入java.util.Arrays。

- 查看更多信息https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(int[],%20int)

的链接