java.util.InputMismatchException by reading a double

独自空忆成欢 提交于 2019-12-13 07:12:30

问题


I got the an java.util.InputMismatchException when I try to read 0.6 here is a part of the code. As you can see i try to reimplement a SkipList for a exercise sheet.

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double f = scan.nextDouble();
        impl_with_errors list = new impl_with_errors(f);
        int n = scan.nextInt();


public class impl_with_errors {
    public static double chance;
    public Node list0;
    public Node list1;
    public Node list2;
    public Node list3;
/**
 * the constructor of the skiplist
 * @param p the chance that an element shall be in a higher list
 */
    public impl_with_errors(double p) {
        chance = p;
        list0 = null;
        list1 = null;
        list2 = null;
        list3 = null;
    }

回答1:


From the docs:

public double nextDouble()

Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.

Parsing 0.6 should work, but if you want to enter 0,6 you can use this:

String dstr = scan.nextLine();

dstr = dstr.replace(",", ".");

double f = Double.parseDouble(dstr);



回答2:


Your code will work just try to modify these lines in the main method:

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter the double value:\n");
    double f = scan.nextDouble();
    impl_with_errors list = new impl_with_errors(f);
    System.out.println("Enter the integer value:\n");
    int n = scan.nextInt();

It should work.




回答3:


Use a comma as decimal sperator, not a dot. 0,6 works

Format the double value with a DecimalFormat df = new DecimalFormat("#,#");



来源:https://stackoverflow.com/questions/20372814/java-util-inputmismatchexception-by-reading-a-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!