Search code examples
javadoublejava.util.scanner

How to import double values to console through Scanner


whenever i input a double value like 5.9 for either a, b, or c i get a missmatch exception error. my goal is to create a quadratic function by importing values for a, b and c with the Scanner.

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;
        }
    }
    

}

Id appreciate your help! Thanks :D


Solution

  • Are you trying to add a double value with a comma as decimal separator?

    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)
    

    If you wish to support commas as decimal separators, you need to read in as Strings and handle it yourself:

    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 ]