Почему мой код отображает один и тот же вывод каждый раз? - PullRequest
0 голосов
/ 05 марта 2020

Я должен закончить с кодом, который отображает название цветка и растет ли он на солнце или в тени. Мне дали 2 файла. Файл, из которого я должен взять данные, называется flowers.dat и содержит следующие данные:

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

Я получил этот код

// 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. 

Вывод, который я получаю отображает все как растущее в тени. Например, в нем говорится: «Бархатцы выращивают в тени. Солнце выращивают в тени» и так далее. Чего мне не хватает?

1 Ответ

2 голосов
/ 05 марта 2020

Все, что вы делаете, это перепечатываете переменную.

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

Пересмотрите ваш l oop, чтобы вы всегда могли прочитать эти значения.

do {
    flowerName = br.readLine();
    if(flowerName == null) {
        break;
    }
    flowerPosition = br.readLine();
    System.out.println(flowerName + " is grown in the " + flowerPosition);
} while(true);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...