我正在编写一个程序,允许用户在文本文件中输入多达9999个帐户,但是我遇到的问题是可以按任何顺序放置它们,但是我必须按顺序打印它们。这是我的代码

import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.text.*;
public class CreateBankFile {

    public static int lines = 0;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Path file = Paths.get("/root/sandbox/BankAccounts.txt");

        String line = "";
        int acctNum = 0;
        String lastName;
        double bal;
        final int QUIT = 9999;

        try
        {
            OutputStream output = new BufferedOutputStream(Files.newOutputStream(file));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));

            while(acctNum != QUIT)
            {
                System.out.print("Enter the acct num less than 9999: ");
                acctNum = input.nextInt();
                if(acctNum == QUIT)
                {
                    continue;
                }
                System.out.print("Enter a last name: ");
                lastName = input.next();
                if(lastName.length() != 8)
                {
                    if(lastName.length() > 8)
                    {
                        lastName = lastName.substring(0, 8);
                    }
                    else if(lastName.length() < 8)
                    {
                        int diff = 8 - lastName.length();
                        for(int i = 0; i < diff; i++)
                        {
                            lastName += " ";
                        }
                    }
                }
                System.out.print("Enter balance: ");
                bal = input.nextDouble();

                line = "ID#" + acctNum + "  " + lastName + "$" + bal;

                writer.write(line);
                writer.newLine();

                lines++;
            }
            writer.close();
        }
        catch(IOException e)
        {
            System.out.println("Error");
        }
    }
}



我的问题是,如何获取它,以便例如在用户输入“ 55”时将其打印到文本文件的第55行?

最佳答案

您可以执行以下操作:

1)创建一个将存储您的行的类(acctNum,lastName ..等)

2)在您的方法中,创建一个您创建的类的数组列表,对于给定的数字“ n”,您的方法将解析所有行,如果acctNum小于“ n”,则将使用此行创建一个新实例,并将其添加到您的数组列表

3)您将使用acctNum对arraylist进行排序,然后打印其内容

10-06 05:53