gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:01:51 27 4
gpt4 key购买 nike

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

我得到的输出显示所有东西都在阴影中生长。例如,它说“万寿菊长在阴凉处。太阳长在阴凉处”等等。我错过了什么?

最佳答案

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

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

关于java - 为什么我的代码每次都显示相同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60553594/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com