0

I'm doing an assignment where I need to read the file, the input of this method should be a file name and the output should be an array of students, the signature method is:

private static Student[] readData(String filename);

My current code is:

import java.io.*;
import java.io.File;
import java.util.Scanner;
class Main{
    public static void main(String[] args) {
        String []text = readData("students.txt");
        for(int i = 0; i<text.length; i++){
            System.out.println(text[i]);
        }
    }

    private static Student[] readData(String filename){
        String[] data = "";
        try{
            File myObj = new File(filename);
            Scanner myReader = new Scanner(myObj);
            while(myReader.hasNextLine()){
                data =myReader.nextLine();
                System.out.println(data);
            }
        }catch (FileNotFoundException e){
            System.out.println("Error");
            e.printStackTrace();
        }
        return data;
    }
}

When I compile the code, it said error "incompatible types: Student[] cannot be converted to String[]". Can you guys explain to me what happens here and how can I fix it?

1 Answer 1

5

You are returning data whose type is String[], however the expected return type of the method is Student[]

Instead of having data as string array, make it a Student[], and add students to this array instead of a string.. instead of

 data[index]= reader.nextLine()

use

data[index] = convertStringToStudent(reader.nextLine())

If required override the toString method in your Student class so that System.out.print(studentInstance) prints the properties you want instead of className@hashcode

Student convertStringToStudent(String input) {
    Student s = new Student();
    // set the properties of student s by parsing input here
    return s;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but when I use the convertStringtoStudent method, it appears error said "cannot find symbol", can you help me with this?
@Peter, its not an inbuilt method, you have to add a method with convertStringToStudent as name which takes in string argument and returns a Student instance, have updated answer
Thanks a lot, I've created the method in my class exactly like yours, but I'm struggling how can I call it back to the main class? Sorry for bothering, I'm pretty new to programming
going by what you say - you have to move the convertStringToStudent to the main class (not in Student java file) and make the method as static. Post the code you have tried so it will be easier to assist

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.