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

2017/3/28

Need help with reading in strings from a text file

Asiantree Asiantree

2017/3/28

#
while (fileReader.hasNext())
        {
            String type = fileReader.nextLine();
            if (type.equals("ant"))
            {
              int xPos, yPos;
              double xVel, yVel;
             
              xPos = fileReader.nextInt();
              yPos = fileReader.nextInt();
             
              xVel = fileReader.nextDouble();
              yVel = fileReader.nextDouble();
             
              Ant nextAnt = new Ant(xVel, yVel);
              addObject(nextAnt, xPos, yPos); 
            }
            if (type.equals("bad"))
            {
                int xPos, yPos;
                 
                xPos = fileReader.nextInt();
                yPos = fileReader.nextInt();
                 
                Fries nextFries = new Fries(50, 50);
                addObject(nextFries, xPos, yPos);
            }
I am having trouble reading from a file to get an ant and bad food (in this case, fries) to spawn into the world. My text file only contains these lines of code as formatted here: ant 300 250 0.7 0.5 bad 100 100 What I am trying to do is get the fileReader to look for the word "ant" and use the line of code to spawn in an ant when it reads that line from the text file. Likewise for the "bad" line in the text file. Any tips on how to read in those words and then use code to get them to spawn into the world? Also, ignore the "new Fries (50, 50)" part.
Nosson1459 Nosson1459

2017/3/29

#
Why are you creating a duplicate of each discussion that you create? You can and should destroy them.
Asiantree Asiantree

2017/3/29

#
I need assistance.
Nosson1459 Nosson1459

2017/3/29

#
I think it would be simpler to have each value on a separate line then you can just do:
try {
    BufferedReader inputFile = new BufferedReader(new FileReader("NameOfFile.txt"));
    int antXPos = Integer.valueOf(inputFile.readLine());
    int antYPos = Integer.valueOf(inputFile.readLine());
    double xVel = Double.valueOf(inputFile.readLine());
    double yVel = Double.valueOf(inputFile.readLine());
    int badXPos = Integer.valueOf(inputFile.readLine());
    int badYPos = Integer.valueOf(inputFile.readLine());
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
For the above code the text file should look like this:
300
250
0.7
0.5
100
100
You need to login to post a reply.