简体   繁体   English

只输出循环的最后一行

[英]Only outputting last line of loop

import java.io.*;
import java.util.Random;

public class LargeDataset {
public static void main(String[] args) throws Exception {
    File file = new File("src/Salary.txt");
    if (file.exists()) {
        System.out.print("Sorry this file already exists.");
        System.exit(0);
    }
    String firstName = "";
    String lastName = "";
    String rank = "";
    double salaryRange = 0.0;

    for (int i = 1; i <= 1000; i++) {
        try (PrintWriter output = new PrintWriter(file))
        {
            firstName = "FirstName" + i;
            lastName = "LastName" + i;
            rank = generateRandomRank();
            if (rank == "assistant")
                salaryRange = generateSalary(50000.00, 80000.00);
            else if (rank == "associate")
                salaryRange = generateSalary(60000.00, 110000.00);
            else
                salaryRange = generateSalary(75000.00, 130000.00);
            output.printf("%s %s %s $%.2f", firstName, lastName, rank, salaryRange);
            output.println();
        }
    }
}

public static String generateRandomRank() {
    String[] rank = {"assistant", "associate", "full"};
    Random random1 = new Random();
    return rank[random1.nextInt(3)];
}

public static double generateSalary(double minSalary, double maxSalary) {
    double randomSalary = minSalary + Math.random() * (maxSalary - minSalary);
    return randomSalary;
 }  
}

Hi everyone.大家好。 I have a program that generates 1000 lines of text and saves it into a file named Salary.我有一个程序可以生成 1000 行文本并将其保存到名为 Salary.txt 的文件中。 The format of each line is: firstNamei, lastNamei, a random rank, and a random salary that is suited to the rank.每行的格式为:firstNamei,lastNamei,一个随机排名,以及一个适合该排名的随机薪水。 However when I run this program it only outputs the 1000th line of the loop.但是,当我运行这个程序时,它只输出循环的第 1000 行。 I noticed however, when I don't put the PrintWriter in the try statement and close it after the loop by myself, it runs fine and generates all 1000 lines.但是,我注意到,当我没有将 PrintWriter 放在 try 语句中并在循环后自行关闭它时,它运行良好并生成所有 1000 行。 Why is it only generating the last line based on how it is right now though?为什么它只根据现在的情况生成最后一行?

You should open your PrintWriter once , and then write to it many times from your loop, not the other way around:您应该打开PrintWriter一次,然后从循环中多次写入,而不是相反:

try (PrintWriter output = new PrintWriter(file)) {
    for (int i = 1; i <= 1000; i++) {
        firstName = "FirstName" + i;
        lastName = "LastName" + i;
        rank = generateRandomRank();
        if (rank == "assistant")
            salaryRange = generateSalary(50000.00, 80000.00);
        else if (rank == "associate")
            salaryRange = generateSalary(60000.00, 110000.00);
        else
            salaryRange = generateSalary(75000.00, 130000.00);
        output.printf("%s %s %s $%.2f", firstName, lastName, rank, salaryRange);
        output.println();
    }
}

You should use the above pattern instead of what you have.你应该使用上面的模式而不是你所拥有的。 If you want an exact fix to your current code, then you may try opening the PrintWriter in append mode:如果您想要对当前代码进行精确修复,那么您可以尝试以附加模式打开PrintWriter

for (int i=1; i <= 1000; i++) {
    try (PrintWriter output = new PrintWriter(new FileOutputStream(file, true)) {
        // same logic
    }
}

This should also work, because now, even though you create a new PrintWriter for each iteration of the loop (inefficient), you open the underlying file in append mode, so each new line should get written properly.这也应该有效,因为现在,即使您为循环的每次迭代创建一个新的PrintWriter (效率低下),您在追加模式下打开底层文件,因此每个新行都应该正确写入。

Every time that you are iterating through your 1000 you are creating a new file每次迭代1000时,您都在创建一个新文件

for (int i = 1; i <= 1000; i++) {
    try (PrintWriter output = new PrintWriter(file))
    ...
}

move it before the loop在循环之前移动它

 try (PrintWriter output = new PrintWriter(file)) {
   for (int i = 1; i <= 1000; i++) {
   }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM