簡體   English   中英

掃描器拋出帶有null的InputMismatchException

[英]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編譯器相同的問題

問題的原因是這樣的

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

這僅是不驗證用戶輸入的示例。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM