我需要编写一个 Java 程序,它将控制台中输入的信息写入 .txt 文件。如果 .txt 文件已经存在,则必须打开它并在另一行写入附加信息。如果新的“升降机”不存在 .txt 文件,它将创建 .txt 并将其写入。基本上我不知道如何为输入的每个名称创建一个新的 .txt 以及如何编辑它,如果人的 .txt 已经存在。我该怎么做呢?
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class MeetPrinter {
public static void getInfo() {
Scanner scanner = new Scanner(System.in);
int question;
String firstName;
String lastName;
int squat;
int bench;
int lift;
String meetName;
do {
System.out.println("Enter first name: ");
firstName = scanner.next();
System.out.println("Enter Last Name: ");
lastName = scanner.next();
System.out.println("Enter new Meet Name: ");
meetName = scanner.next();
System.out.println("Enter max squat weight in kg: ");
squat = scanner.nextInt();
System.out.println("Enter max bench press in kg: ");
bench = scanner.nextInt();
System.out.println("Enter max deadlift in kg: ");
lift = scanner.nextInt();
System.out
.println("Enter '1' to enter more lifters or '2' if you are done entering.");
question = scanner.nextInt();
} while (question == 1);
try{
PrintWriter out = new PrintWriter("output.txt");
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100000);
out.println(lastName + ", " + firstName + " Record #: " + randomInt);
out.println("");
String meet = "Meet Name";
String sq = "SQ Max";
String bp = "BP Max";
String sub = "SUB Total";
String dl = "DL Max";
String tot = "Total";
out.printf("%20s %15s %18s %19s %18s %18s",meet ,sq,bp,sub,dl,tot);
out.println("");
out.printf("%20s", meetName);
out.printf("%10d (%6.2f)", squat, squat * 2.2);
out.printf("%10d (%6.2f)", bench, bench * 2.2);
float subPounds = (float) ((float)(squat + bench) * 2.2);
out.printf("%10d (%6.2f)", squat + bench, subPounds);
out.printf("%10d (%6.2f)", lift, lift * 2.2);
float tPounds = (float) ((float)(squat + bench + lift) * 2.2);
out.printf("%10d (%6.2f)", squat + bench + lift, tPounds);
out.close();
}catch(IOException e){
e.printStackTrace();
}
}
}