2016-10-29 38 views
0

У меня есть программа, которая читает файл, используя имя файла, указанное пользователем. Все содержимое файла должно быть прочитано и сохранено в массиве. Я, похоже, сделал IO правильно, кроме этой ошибки. Я понимаю, что ошибка, но не уверен, как исправить.Строка не может быть преобразована в массив

EDIT: массив уже определен в файле.

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(); 
    } 
} 

Спасибо за помощь.

+0

Где находятся животные [] array? вам нужно создать новый объект вашего класса Animal для заполнения массива. 'animal [j] = new Animal (ваша строка);' –

+0

Массив Animals [] уже определен в том же файле. – John

+0

Используйте все строки в виде строки или используйте построитель строк. Затем создайте массив, используя длину строки или stringbuilder. Наконец, используйте цикл for с string/stringbuilder. Длина и chaAt (i) – Sedrick

ответ

1

animals - массив Animals, но bufferedReader.readLine() читает строку. Вы должны преобразовать его в Animal. Я не вижу определения вашего класса Animals, но, я думаю, должен быть конструктор, который принимает String как аргумент.

Итак, если я прав, то вы должны в основном написать:

animals[j] = new Animals(bufferedReader.readLine());  
1

Много проблем в вашем коде. Начиная с ввода метода. Также чтение из файла.

public static void main(String[] args) { 
     // TODO code application logic here 
     for(String entry : readFile()) 
     { 
      System.out.println(entry); 
     } 
    } 

    static public String[] readFile()                  
    {                            
     Scanner sc = new Scanner(System.in);                 

     InputStreamReader reader;                     
     System.out.println("Please enter the filename to be read from.");           
     String nameOfFile = sc.nextLine();                   
     try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(nameOfFile)));)                          
     {                           
      //constructed = true; why?                  

      String stringLine; 

      ArrayList<String> arraylist = new ArrayList(); 
      while((stringLine = bufferedReader.readLine()) != null)            
      {                        
       arraylist.add(stringLine);              
      }  
      return arraylist.toArray(new String[0]); 
     } 
     catch (FileNotFoundException ex) 
     {                         
      Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     catch (IOException ex) 
     { 
      Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex); 
     }                         
     return null; 
    }