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

Java 为什么我的代码每次都显示相同的输出?,java,file-io,Java,File Io,我应该以显示花的名称以及它是在阳光下生长还是在阴凉处生长的代码结束。我得到了两份文件。我应该从中获取数据的文件名为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.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. 
我得到的输出显示了在阴影中生长的一切。例如,它说“万寿菊生长在阴凉处,太阳生长在阴凉处”等等。我遗漏了什么?

您所做的只是重新打印变量

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);
您所做的只是重新打印变量

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);

您只需设置一次flowerPosition,并且每次通过循环打印相同的值。为什么您希望它每次打印不同的值?如何更改?我只教过一次如何设置它,因为在循环之前,您已经在每个变量中读取单独的行以进行初始化。您只需要在循环内执行类似的操作。您只需设置一次flowerPosition,并且每次通过循环打印相同的值。为什么您希望它每次打印不同的值?如何更改?我只教过一次如何设置它,因为在循环之前,您已经在每个变量中读取单独的行以进行初始化。你只需要在你的循环中做一些类似的事情。哦,好的!非常感谢。我现在明白了。最初的代码是我被教导的方式,但它不起作用…哦,好吧!非常感谢。我现在明白了。最初的代码是我被教导的方式,但它不起作用。。。