Java 扫描器抛出带有null的InputMismatchException
我运行这个代码块 我插入第一个输入,但每个输入都显示null 然后它崩溃了 有人可以运行它并告诉他是否有同样的问题吗Java 扫描器抛出带有null的InputMismatchException,java,java.util.scanner,inputmismatchexception,Java,Java.util.scanner,Inputmismatchexception,我运行这个代码块 我插入第一个输入,但每个输入都显示null 然后它崩溃了 有人可以运行它并告诉他是否有同样的问题吗 我使用BlueJ编译器问题的原因是 import java.io.*; import java.util.*; public class Main{ public static void main(String [] args) throws InputMismatchException{ double width; int period; do
我使用BlueJ编译器问题的原因是
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();
}
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);
当您创建扫描仪时,您在系统上工作。在
中,然后将其关闭。这导致下一个扫描仪在封闭流上运行
解决方案是为InputStream
创建一个扫描仪
in0.close();
...
in1.close();
...
in2.close();
这是唯一一个不验证用户输入的示例 为什么有多个扫描仪实例?如何知道它显示“null”?你是用逗号还是点来输入你的双精度数字的?那个程序不可能显示“null”。首先,它甚至不尝试显示输入。如果您希望我们帮助您,请清楚准确地描述您的问题。请阅读以下内容:
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();