簡體   English   中英

印刷陣列法

[英]Printing array method

我正在嘗試打印我的方法calSum和calMean。 我想得到類似的輸出:

Java RandomArray 8

0 9 5 3 5 6 0 8

總計:36

平均值:4.5

但相反,我得到了-用法:java RandomArray。 示例:java RandomArray 5

我在printArray方法中做錯了嗎? 或者是別的什么? 對我代碼中的錯誤的任何幫助都將非常有用。

    public class RandomArray {

private int[] numbers; //instance variable

/**
 *  Constructor
 *
 *The size of the array
 */
public RandomArray(int size){
    numbers = new int[size];
    for(int i=0; i<numbers.length;i++){
        numbers[i] = (int)(Math.random()*10); // a random number between 0-9
    }
}

/**
 *  a method to print the array elements
 */

public void printArray() {
    for (int i = 0; i < numbers.length; i++)
        System.out.print("Java Random array:"+ numbers);
        System.out.println("Sum:" + calSum());
        System.out.println("Mean:" + calMean());
}       

/**
 *  A method to calculate the sum of all elements
 *
 */
public int calSum(){
 int sum = 0;
 for (int value : numbers) {
     sum += value;
}
    return sum;

}

/**
 *  A method to calculate the mean of all elements
 *
 *@return    The mean
 */

public double calMean() {
    int sum = calSum();
    int length = numbers.length;

    return (double) sum / length;
}


/**
 *  a method to print the array elements in reverse order
 */
public void printReverse(){


}

/**
 *  A main method to test
 */
public static void main(String[] args) {
    // Check to see if the user has actually sent a paramter to the method
    if (args.length != 1){
        System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
        System.exit(-1);
    }

    // Create an instance of the class 
    RandomArray test = new RandomArray(Integer.parseInt(args[0]));


    // Print the array
    test.printArray();

    // Calculate the sum of all the values in the array and print it
    System.out.println("Sum: "+ test.calSum());

    // Calculate the mean of all the values in the array and print it
    System.out.println("Mean: "+ test.calMean());

    System.out.print("Reverse: ");
    test.printReverse();
}

 }

運行主類時, main方法接受String類型的元素數組。

您必須記住,即使在IDE中運行該調用,其外觀也類似於java RandomArray arg1 arg2 該數組包括java之后的所有元素,甚至包括RandomArray

因此, args將始終由至少1個元素組成。 如果需要值arg1 ,則需要獲取args[1]而不是args[0]

您的代碼應如下所示:

public static void main(String[] args) {
    // Check to see if the user has actually sent a paramter to the method
    if (args.length != 2){
        System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
        System.exit(-1);
    }

    // Create an instance of the class 
    RandomArray test = new RandomArray(Integer.parseInt(args[1]));

...

接下來,在打印generate數組時不會獲得預期的結果。 檢查注釋中的鏈接以查看如何正確打印陣列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM