gpt4 book ai didi

java - 编辑异常 e 以捕获字母而不是小数

转载 作者:行者123 更新时间:2023-12-01 13:38:42 24 4
gpt4 key购买 nike

我正在编写一个程序,该程序接受 10 个 float 作为输入。但是,每当我输入小数时,程序都会向我发送错误。我的问题是:如何编辑当前的 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;





}

}

最佳答案

您正在使用 nextInt() 函数,该函数仅返回整数。整数不能保存小数。请查阅 API 并查看 nextFloat() 和 nextDouble() 方法。

关于java - 编辑异常 e 以捕获字母而不是小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com