[英]Java - Scanner throws Exception
我将程序从String 变量更改为StringBuffer 。
我之前在这个程序中使用了一个扫描仪,第一个正常工作,只有第二个出现问题。
Scanner sb = new Scanner(System.in);
replaceFind = replaceFind.append(sb.nextLine());
sb.close();
那是我的扫描仪本身的代码。
StringBuffer buff = new StringBuffer(text), replaceFind = new StringBuffer();
下一个是我使用的变量。
最后我将发布自动抛出的异常:
线程“main”中的异常 java.util.NoSuchElementException: No line found
在 java.util.Scanner.nextLine(未知来源)
在 com.stoeger.StringUebung.insertNewText(StringUebung.java:143)
在 com.stoeger.StringUebung.(StringUebung.java:45)
在 com.stoeger.TheMain.main(TheMain.java:6)
这是我使用的第二个扫描仪,它工作正常:
String find = null;
Scanner sb = new Scanner(System.in);
find = sb.nextLine();
sb.close();
例外来自 sb.nextLine()。 您可以在调用 sb.nextLine() 之前检查 sb.hasNextLine(),这必须避免您面临的异常。
我的问题的解决方案:我的程序中有 2 个扫描仪,这引发了异常。
我把我的 Scanner 作为全局变量(私有),在程序最后关闭它,现在我可以正常使用它了。
Scanner sb = new (System.in);
StringBuffer replaceFind = new StringBuffer();
while (sb.hasNextLine())
replaceFind = replaceFind.append(sb.nextLine());
sb.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.