Я пишу программу, которая принимает 10 чисел с плавающей запятой в качестве входных данных. Однако всякий раз, когда я ввожу десятичную дробь, программа выдает мне ошибку. У меня вопрос: как бы я отредактировал свое текущее исключение try-catch, чтобы поймать только буквы и т. д., и разрешить ввод десятичных знаков (а затем сохранить их в массив). Кроме того, независимо от этой проблемы, моя программа также много раз выводит среднее значение и всегда говорит, что оно равно 0.
Ниже представлена программа:
import java.util.Scanner;
средний общественный класс {
public static void main(String[] args) {
new Average().average(new double[10]);
}
public double average(double[] number) {
Scanner scanner = new Scanner(System.in);
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
int numberIndex = 0;
int largerIndex = 0;
System.out.printf("Please enter 10 floating-point numberes.\nIf more than 10 values are entered, the numbers following 10 are ignored.\nIf less than 10 numbers are entered, the program will wait for you to enter 10.\n");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
sum += numberList[x]; //add up all inputs to find sum
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
numberIndex = 0;
largerIndex = 0;
numberList = new double[10];
largerList = new double[10];
continue;
}
}
for (int i = 0; i < number.length; i++) {
sum = sum + number[i];
double average = sum / number.length;
//return average;
if (x > average) {
largerList[largerIndex] = x; //add negative input to negativeList array
largerIndex = largerIndex + 1;
}
System.out.println("Average value of your input is: " + average);
System.out.println();
}
for (int i = 0; i < largerIndex; i++) {
System.out.println(largerList[i]);
}
return 0;
}
}
catch
, вы указываете только тип исключения. Если вы хотите, чтобы исключения выбрасывались (или не выбрасывались) только при определенных обстоятельствах, вы должны подготовить код для предварительного тестирования по мере необходимости, прежде чем исключение может быть выброшено. - person Hot Licks   schedule 10.01.2014