Search code examples
javajava.util.scannerinputmismatchexception

Scanner throws InputMismatchException with null


import java.io.*;
import java.util.*;

public class Main{
    public static void main(String [] args) throws InputMismatchException{
    double width;
    int period;
    double Ppp;
    Scanner in0  = new Scanner(System.in);
    Scanner in1  = new Scanner(System.in);
    Scanner in2  = new Scanner(System.in);
    System.out.println("Give width\n");
    while(in0.hasNextDouble()){
        width = in0.nextDouble();
    }
    in0.close();
    System.out.println("\n");
    System.out.println("Give period");
    while(in1.hasNextInt()){
        period = in1.nextInt();
    }
    in1.close();
    System.out.println("\n");
    System.out.println("Insert width peak to peak");
    while(in2.hasNextDouble()){
        Ppp = in2.nextDouble();
    }
    in2.close();
}

I run this code block I insert the first input but it displays null for each input and then it crash May someone run it and tell if he has the same problem I use BlueJ compiler


Solution

  • public static void main(String [] args) throws InputMismatchException{
        double width;
        int period;
        double Ppp;
        Scanner in0  = new Scanner(System.in);
    
        System.out.println("Give width\n");
        // This will read the line, and parse the result as a double, this way you can insert a number and press enter
        width = Double.parseDouble(in0.nextLine());
    
        System.out.println("Give period");
        period = Integer.parseInt(in0.nextLine());
    
        System.out.println("\n");
        System.out.println("Insert width peak to peak:");
        ppp = Double.parseDouble(in0.nextLine());
    
        in0.close();
        }