为什么我的代码每次都显示相同的输出?

问题描述 投票:0回答:1

我应该以显示花名以及是否在阳光或阴影下生长的代码结尾。我得到了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. 

我得到的输出显示所有内容都在阴影中增长。例如,它说“万寿菊在树荫下生长。太阳在树荫下生长”等等。我想念什么?

java file-io
1个回答
2
投票

您要做的就是重新打印变量。

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

重做循环,以便始终可以读取这些值。

do {
    flowerName = br.readLine();
    if(flowerName == null) {
        break;
    }
    flowerPosition = br.readLine();
    System.out.println(flowerName + " is grown in the " + flowerPosition);
} while(true);
© www.soinside.com 2019 - 2024. All rights reserved.