扫描仪NoSuchElementException
我的Java分配有问题。 我遇到了一个意想不到的exception,特别是:
java.util.NoSuchElementException:找不到行
我正在使用Scanner(System.in)
,程序不断读取任何内容并重复“无效格式”exception文本。 如果我输入一个正确值int
,第一部分通过,然后double
部分立即进入此exception。 如果我输入一个错误值的int
,那么它开始循环exception。
这是我的代码:
import java.util.Scanner; public class Program_4 { public static void main(String[] args) { getValidInt("Enter an integer from 5 to 50",5,50); getValidDouble("Enter a double from 5.0 to 50.0",5.0,50.0); getValidString("Enter a string with length from 5 to 8 characters",5,8); } public static int getInt(String prompt) { Scanner sc = new Scanner(System.in); int i = 0; boolean isValid; do { try { System.out.print(prompt + ": "); i = Integer.parseInt(sc.nextLine()); isValid = true; } catch (Exception e) { System.out.println(e); System.out.print("Invalid Format: "); isValid = false; } } while (isValid == false); sc.close(); return i; } public static int getValidInt(String prompt, int min, int max) { int i = 0; boolean isValid = false; do { i = getInt(prompt); if(i = " + min); else if(i > max) System.out.println("Value must be <= " + max); else isValid = true; } while (isValid == false); return i; } public static double getDouble(String prompt) { Scanner sc = new Scanner(System.in); double i = 0.0; boolean isValid; do { try { System.out.print(prompt + ": "); i = Double.parseDouble(sc.nextLine()); isValid = true; } catch (Exception e) { System.out.println(e); System.out.println("Invalid Format: "); isValid = false; } } while (isValid == false); sc.close(); return i; } public static double getValidDouble(String prompt, double min, double max) { int i = 0; boolean isValid = false; do { i = getInt(prompt); if(i = " + min); else if(i > max) System.out.println("Value must be <= " + max); else isValid = true; } while (isValid == false); return i; } public static String getString(String prompt) { Scanner sc = new Scanner(System.in); String i=""; boolean isValid; do { try { System.out.print(prompt + ": "); i = sc.nextLine(); isValid = true; } catch (Exception e) { System.out.print("Invalid Format: "); isValid = false; } } while (isValid == false); sc.close(); return i; } public static String getValidString(String prompt, int min, int max) { String i; boolean isValid = false; do { i = getString(prompt); if(i.length() max) System.out.println("String must be more than " + max + " characters."); else isValid = true; } while (isValid == false); return i; } }
您关闭了多个Scanner
,这会关闭基础InputStream
,因此另一个Scanner
无法再读取相同的InputStream
和NoSuchElementException
结果。
对于控制台应用程序,请使用单个Scanner
从System.in
读取。
由于您在捕获exception的所有三个地方打印出相同的消息,因此很难确切地说出发生了什么:
-
使用
printStackTrace()
来查找exception发生的位置 -
不要像那样捕获
Exception
。 捕获您期望的exception以及您的代码旨在处理的exception。 如果您捕获Exception
您最终可能会捕获各种意外exception(NPE,文件结尾等)……并错误地将它们报告为“无效格式”。