我正在讀取文件並將其複製到數組中。我的文件有五行文字,每句都有一個句子。我得到我的輸出「數組大小是5」,但之後沒有。如果我添加了陣列的打印線,它會給我5個空值...從文本文件讀入數組 - 獲取「空值」
有人可以幫助解釋我做錯了什麼嗎?謝謝!
public static int buildArray() throws Exception
{
System.out.println("BuildArray is starting ");
java.io.File textFile; // declares a variable of type File
textFile = new java.io.File ("textFile.txt"); //reserves the memory
Scanner input = null;
try
{
input = new Scanner(textFile);
}
catch (Exception ex)
{
System.out.println("Exception in method");
System.exit(0);
}
int arraySize = 0;
while(input.hasNextLine())
{
arraySize = arraySize + 1;
if (input.nextLine() == null)
break;
}
System.out.println("Array size is " + arraySize);
// Move the lines into the array
String[] linesInRAM = new String[arraySize];// reserve the memory
int count = 0;
if (input.hasNextLine())
{
while(count < arraySize)
{
System.out.println("test");
linesInRAM[count] = input.nextLine();
System.out.println(linesInRAM[count]);
count = count + 1;
}
}
你永遠不會重置掃描儀,所以它直到在文件的結尾... – MadProgrammer 2014-10-22 02:50:46