只输出循环的最后一行 [英] Only outputting last line of loop

查看:58
本文介绍了只输出循环的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

大家好.我有一个程序,该程序生成1000行文本并将其保存到名为Salary的文件中.每行的格式为:firstNamei,lastNamei,随机排名和适合该排名的随机薪水.但是,当我运行此程序时,它仅输出循环的第1000行.但是,我注意到,当我没有将PrintWriter放在try语句中并由我自己在循环后将其关闭时,它运行良好并生成了所有1000行.为什么为什么只根据当前情况生成最后一行?

Hi everyone. I have a program that generates 1000 lines of text and saves it into a file named Salary. The format of each line is: firstNamei, lastNamei, a random rank, and a random salary that is suited to the rank. However when I run this program it only outputs the 1000th line of the loop. 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. Why is it only generating the last line based on how it is right now though?

推荐答案

您应该打开 PrintWriter 一次,然后从循环中多次写入它,而不是相反:

You should open your PrintWriter once, and then write to it many times from your loop, not the other way around:

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

您应该使用上面的模式代替现有的模式.如果您想对当前代码进行精确修复,则可以尝试在附加模式下打开 PrintWriter :

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:

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

这也应该起作用,因为现在,即使您为循环的每次迭代创建了一个新的 PrintWriter (效率低下),也可以在 append 模式下打开基础文件,因此每一行都应正确书写.

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.

这篇关于只输出循环的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆