![](/img/trans.png)
[英]java.util.NoSuchElementException even though hasMOreTokens included
[英]java.util.NoSuchElementException even though input file has data
我已經編寫了這段代碼來查找輸出,並且正在servlet中使用運行時來運行它。 即使我檢查了輸入文件是否包含一些數據,它也會顯示java.util.NoSuchElementEception:
public class Sec1q10 {
static int fact(int n) {
int p = 1;
if (n != 1) {
p = n * fact(n - 1);
}
return p;
}
public static void main(String args[]) {
try {
System.out.println("first");
Scanner in = new Scanner(new FileReader("F:/sem5/algorithm/in.txt"));
String no = in.next();
int n = Integer.parseInt(no);
System.out.println(n);
int s = 0;
while (n != 0) {
s += fact(n);
n--;
}
System.out.println("sum=" + s);
String s1 = "" + s + "here";
PrintWriter out;
System.out.println(s1);
out = new PrintWriter("F:/sem5/algorithm/out.txt");
out.write(s1);
System.out.println(s1);
} catch (Exception ex) {
System.out.println("Exception: " + ex);
}
}
}
我什至在cmd上運行此命令,該命令顯示輸出無任何異常,但未在文件F:/sem5/algorithm/out.txt中寫入任何內容
每當您使用Scanner
類時,您都應該進行實際測試,以確保在嘗試使用hasNextXXXXX()
方法讀取輸入之前,輸入正在等待您。
嘗試這個:
String no;
while(in.hasNext())
{
no = in.next();
//.....
}
問題不在於您的輸入文件沒有任何數據,而是您的輸入文件用完了數據,因為您不斷進行讀取。 如果您嘗試在什么都沒有的情況下閱讀,則會收到NoSuchElementException
我能想到的是該目錄不存在。 您確定嗎? 如果沒有,您應該手動進行,或使用.mkdir()
函數
要看到在輸出文件關閉結果PrintWriter
寫在它之后
PrintWriter out;
System.out.println(s1);
out = new PrintWriter("F:/sem5/algorithm/out.txt");
try
{
out.write(s1);
System.out.println(s1);
}
finally
{
out.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.