我正在编写一个以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;
}
}
答案 0 :(得分:1)
您正在使用nextInt()函数,该函数仅返回整数。 Int不能包含小数。请参考API并查看nextFloat()和nextDouble()方法。
答案 1 :(得分:0)
对于您的平均问题,您的print语句将进入for循环,因此它将执行number.length
次。将print语句移到循环外部。您还需要将平均变量的声明放在循环之外。你也应该只需要循环来计算总和,你不需要每次计算平均值
double average;
for(/*loop conditions*/)
{
sum = sum + number[i];
}
average = sum / number.length;
System.out.println("Average value of your input is: " + average);
System.out.println();