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

标签 java arrays exception floating-point try-catch

我正在编写一个程序,该程序接受 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/

相关文章:

java - SWT 对齐按钮时出现问题

c# - 将字符串数组中的值分配给自定义类型数组的每个元素的字符串属性

c# - 如何遍历动态类型数组

c# - 如何处理 javascript Web 应用程序在 C# 中抛出的异常?

java - 异常(exception)对所有异常(exception)都有效吗?

c# - 在 C++ 和 C# 中使用 try/catch 的正确方法是什么?

java - Java 中的安全 ID 具有持久性

java - Reactive Mongo - DeleteAllBy...查询 - 找不到类型类 java.lang.Void 的 PersistentEntity

java - 使用 OpenCSV 写入列而不是行

php - 有条件地将关联元素添加到数组