扫描器抛出 InputMismatchException 为 null

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

我运行这个代码块 我插入第一个输入,但它为每个输入显示 null 然后它崩溃了 让某人 运行 告诉他是否有同样的问题 我使用 BlueJ 编译器

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

问题的原因是这个

Scanner in0  = new Scanner(System.in);
Scanner in1  = new Scanner(System.in);
Scanner in2  = new Scanner(System.in);

还有这个

in0.close();
...
in1.close();
...
in2.close();

创建扫描仪时,您会处理 System.in,然后关闭它。这导致下一个扫描器在关闭的流上运行。

解决方案是为 InputStream 创建一个 Scanner

Scanner scanner = new Scanner(System.in);

System.out.println("Give width\n");
double width = scanner.nextDouble();

System.out.println("Give period");
int period = scanner.nextInt();

System.out.println("\nInsert width peak to peak:");
double p2p = scanner.nextDouble();

这只是不验证用户输入的示例。