Как использовать исключение для обработки ввода размера массива и элементов, которые можно использовать для расчета среднего? - PullRequest
0 голосов
/ 08 мая 2020

Моя программа позволит пользователю вводить размер массива и элементы внутри массива. Моя проблема заключается в том, что когда вводится отрицательное число размера массива, он все еще продолжает вводить элементы, а не InputMismatchException, который будет предлагать пользователю ввести снова. Я новичок в Java и, пожалуйста, помогите мне

publi c class Lab5Class {

    public static double avgArry(double[] a) {
        double sum = 0;
        double average = 0;

        for(double numbers: a) {
            sum+=numbers;
            average = sum / a.length;
        }

        return average;
}   

    public static void main(String[] args) {
        // TODO Auto-generated method stub
       int attempt = 1;
       int size;

    do {  
       try {
           System.out.println("Enter the size of the array : ");
           Scanner input = new Scanner(System.in);
            size = input.nextInt();
           double myArray[] = new double[size];
         System.out.println("Enter the elements of the array one by one: " );
           for(int i = 0;i<size; i++) {
           myArray[i] = input.nextDouble();
           }
           System.out.println("Contents of the array are: "+Arrays.toString(myArray));
           attempt++;
       }catch(InputMismatchException e) {
           System.out.println("Invalid Input! Please try again");
       }
       }while(attempt == 1); 

}
}

Ответы [ 5 ]

0 голосов
/ 08 мая 2020

Если необходимо выбросить исключение, то после

 size = input.nextInt();

добавьте

if (size <= 0) {
    throw new InputMismatchException("Array size must be larger than 0");
}
0 голосов
/ 08 мая 2020

См. Ниже реализацию вашего Lab5Class. Он просит пользователя повторно ввести значения, которые не являются числами (путем перехвата InputMismatchException). Он также продолжает просить пользователя ввести размер массива, пока [s] он не введет положительное число. После ввода всех необходимых значений отображается содержимое массива и среднее значение.

import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Lab5Class {
    public static double avgArry(double[] a) {
        double sum = 0;
        double average = 0;

        for (double numbers : a) {
            sum += numbers;
            average = sum / a.length;
        }

        return average;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int size = 0;
        while (size <= 0) {
            System.out.print("Enter the size of the array: ");
            try {
                size = input.nextInt();
                if (size <= 0) {
                    System.out.println("   Size must be positive. PLease try again.");
                }
            }
            catch (InputMismatchException e) {
                System.out.println("   Invalid Input! Please try again");
            }
            input.nextLine();
        }
        double myArray[] = new double[size];
        System.out.println("Enter the elements of the array one by one: ");
        for (int i = 0; i < size; i++) {
            System.out.print("Enter element " + i + ": ");
            try {
                myArray[i] = input.nextDouble();
            }
            catch (InputMismatchException e) {
                i--;
                System.out.println("   Invalid Input! Please try again");
            }
            input.nextLine();
        }
        System.out.println("Contents of the array are: " + Arrays.toString(myArray));
        System.out.println("average = " + avgArry(myArray));
    }
}
0 голосов
/ 08 мая 2020

Можно попробовать что-то подобное. Выполните рефакторинг под свои нужды

        for (int i = 0; i < size; i++) {
      boolean flag;
      do {
        double temp = input.nextDouble();
        if (temp < 0) {
          System.err.println("Number must be greater than zero");
          flag = false;
        } else {
          myArray[i] = temp;
          flag = true;
        }
      } while (!flag);
    }
0 голосов
/ 08 мая 2020

Вместо этого вы можете просто объединить оператор if и while-l oop, например

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int attempt = 1;
    int size;
    Scanner input = new Scanner(System.in);

    boolean correctSize = false;

    System.out.print("Enter the size of the array : ");
    size = input.nextInt();
    if (size <= 0) {
        while (!correctSize) {
            System.out.print("ERROR:Size cannot be less than zero, please enter a number greater than zero:");
            size = input.nextInt();
            if (size > 0) {
                correctSize = true;
            }
        }
    }

    double myArray[] = new double[size];
    System.out.println("Enter the elements of the array one by one: ");
    for (int i = 0; i < size; i++) {
        myArray[i] = input.nextDouble();
    }
    System.out.println("Contents of the array are: " + Arrays.toString(myArray));
    attempt++;

}

Существует исключение под названием «NegativeArraySizeException», но вы не захотите его использовать, поскольку пользователю будет предложено снова ввести размер. Посетите этот веб-сайт, если хотите узнать о нем больше.

0 голосов
/ 08 мая 2020

Нет, вы не можете использовать отрицательное целое число в качестве размера, размер массива представляет количество элементов в нем.

Тем не менее, если вы это сделаете, программа будет компилироваться без проблем, но при ее выполнении генерирует исключение времени выполнения типа NegativeArraySizeException

Пример:

public class Test {
   public static void main(String[] args) {
      int[] intArray = new int[-5];
   }
}

Вывод:

Exception in thread "main" java.lang.NegativeArraySizeException
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...