我有一個程序使用用戶指定的文件名讀入文件。 必須讀取所有文件內容並將其存儲在數組中。除了這個錯誤之外,我似乎已經正確地完成了IO。我明白錯誤是什麼,但不知道如何糾正。字符串不能轉換爲數組
編輯:該數組已在文件中定義。
Zoo.java:284: error: incompatible types: String cannot be converted to Animals
animals[ j ] = bufferedReader.readLine();
這裏是我的READFILE子模塊代碼:
public String readFile(Animals[] animals)
{
Scanner sc = new Scanner(System.in);
String nameOfFile, stringLine;
FileInputStream fileStream = null;
BufferedReader bufferedReader;
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
nameOfFile = sc.nextLine();
try
{
constructed = true;
fileStream = new FileInputStream(nameOfFile);
bufferedReader = new BufferedReader(new InputStreamReader(fileStream));
while((stringLine = bufferedReader.readLine()) != null)
{
for(int j = 0; j < animals.length; j++)
{
animals[j] = bufferedReader.readLine();
}
}
fileStream.close();
}
catch(IOException e)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in file processing: " + e.getMessage();
}
}
感謝您的幫助。
動物[]數組在哪裏定義?你必須創建你的Animal類的新對象來填充數組。 '動物[j] =新動物(你的線);' –
動物[]數組已經定義在同一個文件中。 – John
使用將所有行讀取爲字符串,或使用字符串構建器。接下來使用字符串或stringbuilder的長度來創建你的數組。最後,在string/stringbuilder中使用for循環。長度和字符(i) – Sedrick