java打印数组方法

ddrv8njm  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(389)

我正在试着打印出我的方法calsum和calmean。我想得到一个类似的输出:
java随机数组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();
}

 }
jm81lzqq

jm81lzqq1#

当你运行主类时 main 方法接受类型为的元素数组 String .
你要记住这个电话看起来像 java RandomArray arg1 arg2 ,即使在ide中运行它。数组包括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数组时将不会得到预期的结果。检查注解中的链接以查看如何正确打印数组。

相关问题