Метод печатного массива - PullRequest
       24

Метод печатного массива

0 голосов
/ 06 декабря 2018

Я пытаюсь распечатать мои методы 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();
}

 }

1 Ответ

0 голосов
/ 06 декабря 2018

Когда вы запускаете основной класс, метод 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]));

...

Далее вы не получитеожидаемый результат при печати сгенерированного массива.Проверьте ссылку в комментариях, чтобы увидеть, как правильно распечатать массив.

...