This site requires JavaScript, please enable it in your browser!
Greenfoot back
gd_deception
gd_deception wrote ...

2021/11/13

What should be a string seems to have become a list...?

gd_deception gd_deception

2021/11/13

#
I've implemented the file reader code from this scenario into my own project. The section of code used is as follows:
    public static java.util.List<String> loadFile(String filename) {
        ArrayList<String> fileText = new ArrayList<String>();
        BufferedReader file = null;
        try {
            file = new BufferedReader(new FileReader(filename));
            String input;
            while ((input = file.readLine()) != null) {
                fileText.add(input);
            }
        }
        catch (FileNotFoundException fnfe) {
            //fnfe.printStackTrace();
            return null;
        }
        catch (IOException ioe) {
            //ioe.printStackTrace();
            return null;
        }
        finally {
            try {
                file.close();
            }
            catch (IOException ioe) {
                ioe.printStackTrace();
            }
            catch (NullPointerException npe) {
                //npe.printStackTrace();
            }
        }
        return fileText;
    }
Upon trying to call this method in a different class, I get no errors. In order to display the text, I use the addObject method like so:
addObject(new TextObj(Reader.loadFile("data/nationdata.txt")),300,200);
(TextObj just has a single line of code that sets its image to the given text.) I am given the error "java.util.List<java.lang.String> cannot be converted to java.lang.String, which I presume means that the parameter I gave when calling the loadFile method was not in fact a string. I tried using the toString method and creating a string variable, however both return the same error. I should also probably mention that I do not understand most of what is in the loadFile method. Is there any sort of way I can fix this?
danpost danpost

2021/11/13

#
gd_deception wrote...
I am given the error "java.util.List<java.lang.String> cannot be converted to java.lang.String, which I presume means that the parameter I gave when calling the loadFile method was not in fact a string.
Correct -- it is not a String object. It is a List object that happens to contain one element that happens to be a String object. Use:
addObject(new TextObj(Reader.loadFile("data/nationdata.txt").get(0))), 300, 200);
This (with the ".get(0)") will return (get) the first String element from the list.
You need to login to post a reply.