如何通过 Scanner 将双精度值导入控制台

How to import double values to console through Scanner

每当我为 a、b 或 c 输入双精度值(如 5.9)时,我都会收到不匹配异常错误。我的目标是通过使用扫描仪导入 a、b 和 c 的值来创建二次函数。

import java.util.Scanner;
public class Main {
    static Scanner scan = new Scanner(System.in);
    public static void main(String[] args) {
        Wrappers.quadraticWrapper(scan);

    }
    static class Wrappers {
        public static void quadraticWrapper(Scanner s){
            System.out.print("Insert for a: ");
            double a = s.nextDouble();
            System.out.print("insert for b: ");
            double b = s.nextDouble();
            System.out.print("insert for c: ");
            double c = s.nextDouble();
            printArr(Formulas.quadraticF(a, b, c));
        }
        private static void printArr(double[] arr) {
            System.out.println("[");
            for (double d : arr) {
                System.out.print(d + " ");
            }       System.out.println("]");

        }
    }
    static class Formulas{
        public static double[] quadraticF(double a, double b, double c) {
            double[] arr = new double[2];
            double x1, x2;
            x1 = (-b + Math.sqrt(Math.pow(b, 2) - ((4) * (a) * (c))))/(2 * a);
            x2 = (-b - Math.sqrt(Math.pow(b, 2) - ((4) * (a) * (c))))/(2 * a);
            arr[0] = x1;
            arr[1] = x2;
            return arr;
        }
    }
    

}

感谢您的帮助!谢谢 :D

您是否尝试添加以逗号作为小数点分隔符的双精度值?

Insert for a: 5,6
Exception in thread "main" java.util.InputMismatchException
        at java.util.Scanner.throwFor(Scanner.java:864)
        at java.util.Scanner.next(Scanner.java:1485)
        at java.util.Scanner.nextDouble(Scanner.java:2413)
        at Main$Wrappers.quadraticWrapper(Main.java:11)
        at Main.main(Main.java:5)

如果你希望支持逗号作为小数点分隔符,你需要读入字符串并自行处理:

double c = commaNumberToDouble(s.nextLine());
private static double commaNumberToDouble(String input) {
    return Double.parseDouble(input.replaceAll(",", "."));
}
% java Main
Insert for a: 4,5
insert for b: 24.6
insert for c: 1,2
[
-0.0492237147736808 -5.417442951892986 ]