[英]Why doesn't .size() work properly on this ArrayList?
我已經將dat文件導入到ArrayList中。 我的問題是,盡管它會打印出文件中的所有名稱,但不會給我正確的大小。 相反,它只是打印出1。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class TestArray {
public static void main (String [] args){
String filePath = "C:\\Users\\Admin\\workspace\\Fund III\\src\\names.dat";
Scanner sc = null;
try {
sc = new Scanner(new File (filePath ));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Makes Array list
ArrayList<String> nameList = new ArrayList<String>();
//Dumps names into array
try{
while(sc.hasNextLine())
{
nameList.add(sc.nextLine());
}
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
System.out.println(nameList.size());
System.out.println(nameList);
}
}
您的文件似乎只有一行。 這是檢查方法:
while(sc.hasNextLine()) {
String line = sc.nextLine();
nameList.add(line);
System.out.println("Line: '"+line+"'");
}
運行修改后的程序,並注意字符串周圍的單引號。 如果您的輸出在單引號對內產生多行,則問題在於您的輸入沒有運行程序的系統所期望的行尾標記。
根據掃描儀的 Java文檔...
掃描儀使用的默認空格分隔符由Character.isWhitespace識別。
您確定您了解文件的內容以及如何創建文件(Linux / Windows)。
例如,當在Linux上運行Java進程並讀取在Windows上創建的文件時,我經常不得不使用dos2unix命令來更正文件格式,否則除非您付出額外的精力來指定文件名,否則它將無法按預期進行處理。 Java代碼中正確的文件編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.