[英]Reading Digits/Integer from File in Java
我正在嘗試計算文件中的所有整數,但由於這個.toCharArray();
我不斷收到錯誤.toCharArray();
和.length()
; 他們都是“它找不到符號 - 方法 toCharArray()”?
public static void main(String[] args){
try{
FileReader f = new FileReader(("numbers.txt")); //replace this to exact location where you store numbers.txt in computer
Scanner input = new Scanner(f);
char[] count = input.toCharArray();
int num = 0;
for (int i =0; i<input.length(); i++){
if(Character.isDigit(count[i])){
num++;
}
System.out.println("There are "+num+" numbers in the file.");
}
} catch(Exception s){
System.out.println(s.getMessage());
}
}
數字.txt:
8 96 54 25
104 19
112 86 73
16 30 112 57
2 26 64 83
65
36 1
25
18 111
56 104 8 36 87
我的預期輸出是這樣的:
> There are 28 numbers in the file.
更新
我只是檢查你的輸入文件。 您計算每個數字的方法是完全錯誤的。 您必須通過white space
將行拆分為單詞數組,並檢查該單詞是否為數字。
您可以通過FileInputStream
讀取文件並逐行處理。 如果您只想計算數字(具有多個數字),或者您可以將一行轉換為字符數組並檢查每個字符,則每行將按white space
拆分為單詞。
這是您需要使用FileInputStream
和BufferReader
兩個類。
該示例基於您的代碼(計數數字)
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line = null;
int count = 0;
//Read File Line By Line
while ((line = br.readLine()) != null) {
for(Character c: line.toCharArray()) {
//check if the c is a digit and increase count
}
}
//Close the input stream
fstream.close();
//return count or print it out.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.