[英]Program unable to read from file and save to variable
當我運行我的代碼時,它說有一個InputMismatchException? 適用於前兩個讀取行,但是我嘗試讀取int和雙行,但不會讀取,並且字符串行實際上未將任何內容讀入變量,它為空,因為它不打印任何內容在system.out.println(a + b)...有什么提示嗎?
import java.util.*;
import java.io.*;
class Uke55{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
try{
PrintWriter utfil=new PrintWriter(new File("minfil55.txt"));
utfil.println('A');
utfil.println("Canis familiaris betyr hund");
utfil.println(15);
utfil.printf("%.2f", 3.1415);
utfil.close();
}catch(Exception e){
e.printStackTrace();
}
try{
Scanner innfil=new Scanner(new File("minfil55.txt"));
char a=innfil.next().charAt(0);
String b=innfil.nextLine();
System.out.println(a +b);
int c=(int)innfil.nextInt();
double d=(double)innfil.nextDouble();
innfil.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
這是因為當您使用next(),nextInt()和nextDouble()時,它不會移至新行。 只有newLine()將光標移動到下一行。 做這個:
try{
Scanner innfil=new Scanner(new File("minfil55.txt"));
char a=innfil.nextLine().charAt(0); //first error was here. calling next() only
//read A and not the \r\n at the end of the
//line. Therefore, the line after this one was
//only reading a newline character and the
//nextInt() was trying to read the "Canis" line.
String b=innfil.nextLine();
System.out.println(a +b);
int c=(int)innfil.nextInt();
innfil.nextLine(); //call next line here to move to the next line.
double d=(double)innfil.nextDouble();
innfil.close();
}
catch(Exception e){
e.printStackTrace();
}
next(),nextInt(),nextDouble(),nextLong()等...都在任何空格(包括行尾)之前停止。
那是因為您有文件:
A\n
Canis familiaris betyr hund\n
15\n
3.14
其中\\n
代表換行符。
第一次打電話時
innfil.nextLine().charAt(0)
它讀取A
,而掃描儀讀取點指向第一個\\n
然后你打電話
innfil.nextLine()
它讀取直到\\n
( nextLine()
讀取直到\\n
並將掃描器讀取指針放在\\n
),並使讀取指針超過\\n
。 讀指針將在下一行的C
。
然后你打電話
innfil.nextInt()
h! 掃描儀無法識別Canis
為整數,輸入不匹配!
根據Scanner.nextLine()上的文檔
“ 將此掃描程序前進到當前行之外,並返回被跳過的輸入。 ”
因此,在調用char a=innfil.next().charAt(0);
“光標”在第一行的末尾。 調用String b=innfil.nextLine();
讀取直到當前行的末尾(沒有要讀取的所有內容),並前進到下一行(實際的String所在的位置)。
解
在調用String b=innfil.nextLine();
之前,需要前進到下一行String b=innfil.nextLine();
:
...
char a=innfil.next().charAt(0);
innfil.nextLine();
String b=innfil.nextLine();
...
注意事項 :
雖然Scanner.nextInt()和Scanner.nextDouble()的行為方式相同Scanner.next() ,你不面對同樣的問題,因為這些方法將讀取下一個完整標記(其中“ 一個完整標記的前后其后跟匹配定界符模式 “) 的輸入和空白字符(例如換行符)都被視為定界符。 因此,如果需要,這些方法將自動前進到下一行,以查找下一個完整的令牌 。
您是否檢查過實際寫入文件的內容? 我不信。 在關閉PrintWriter之前,請嘗試調用flush()。 編輯:對不起,我在這里錯了,因為我在考慮自動行刷新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.