Why is my code displaying the same output every time?

Gabby :

I am supposed to end up with code that displays a flower's name and whether it grows in the sun or the shade. I was given 2 files. The file I am supposed to take the data from is called flowers.dat and includes the following data:

Astilbe
Shade
Marigold
Sun
Begonia
Sun
Primrose
Shade
Cosmos
Sun
Dahlia
Sun
Geranium 
Sun
Foxglove
Shade
Trillium
Shade
Pansy
Sun
Petunia
Sun
Daisy
Sun
Aster
Sun

I have come up with this code

// Flowers.java - This program reads names of flowers and whether they are grown in shade or sun from an input 
// file and prints the information to the user's screen. 
// Input:  flowers.dat.
// Output: Names of flowers and the words sun or shade.

import java.io.BufferedReader;
import java.io.FileReader;

public class Flowers {
    public static void main(String args[]) throws Exception {
        // Declare variables here
        String flowerName, flowerPosition;

        // Open input file.
        FileReader fr = new FileReader("flowers.dat");
        // Create BufferedReader object.
        BufferedReader br = new BufferedReader(fr);
        flowerName = br.readLine();
        flowerPosition = br.readLine();

        // Write while loop that reads records from file.
        while ((flowerName = br.readLine()) != null) {
            System.out.println(flowerName + " is grown in the " + flowerPosition);
        }

        br.close();
        System.exit(0);
    } // End of main() method.

} // End of Flowers class. 

The output that I am getting displays everything as growing in the shade. For instance, it says "Marigold is grown in the Shade. Sun is grown in the Shade" and so on. What am I missing?

Makoto :

All you're doing is reprinting the variable.

System.out.println(flowerName + " is grown in the " + flowerPosition);

Rework your loop so you can always get those values read in.

do {
    flowerName = br.readLine();
    if(flowerName == null) {
        break;
    }
    flowerPosition = br.readLine();
    System.out.println(flowerName + " is grown in the " + flowerPosition);
} while(true);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27031&siteId=1