这是一个单一的分配。
那么,我从哪里开始呢?
任务:任务是制作一个外部 .txt 文件的高级列表。.txt 文件只能有 5 个不同的最高分,这意味着如果我添加一个高于第 5 位高分的高分,则需要删除一个并用新的高分替换。
如果单击类名,您将被重定向到包含代码的粘贴链接。
问题:我无法在不删除当前文本的情况下获得添加文本的代码。代码的当前语句可能是处理问题的错误方式,我不知道。我尝试了几种方法,但似乎没有一个对我有用(或者我做错了)。对列表进行排序应该不是问题,因为我在最近的作业中已经这样做了。
无论如何,闲聊够了,让我们开始做事吧。
我的主要:
public class main {
public static void main(String[] args) {
menu menu = new menu();
menu.display();
}
}
import java.util.*;
public class menu {
highscores highscores = new highscores();
private Scanner input = new Scanner(System.in);
public void display() {
System.out.println("Make your selection!");
System.out.println("Select an option: \n" + " 1) Insert new score\n"
+ " 2) Print list\n" + " 3) Reset list \n" + " 4) Quit\n ");
int selection = input.nextInt();
input.nextLine();
switch (selection) {
case 1:
highscores.enterScore();
break;
case 2:
highscores.printList();
break;
case 3:
highscores.resetList();
break;
case 4:
System.out.println("Exiting program...");
System.exit(1);
default:
System.out.println("Try Again!");
break;
}
}
}
import java.io.*;
import java.util.*;
public class highscores {
public void enterScore() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the players name!: ");
String name = scan.nextLine();
System.out.println("Enter the players score!: ");
String score = scan.nextLine();
System.out.println("Player " + name + " got: " + score
+ " points. Great job!");
try {
File file = new File("HighScores.txt");
PrintWriter writer;
writer = new PrintWriter(file);
writer.println("Player name: " +name +" - " +"Player score:" +score);
writer.close();
} catch (Exception e) {
System.out.println("Error #1");
}
}
public void printList() {
try {
File file = new File("Highscores.txt");
Scanner scanner;
if (file.exists()) {
scanner = new Scanner(file);
for (int i = 0; i < 5; ++i) {
String line = scanner.nextLine();
System.out.println(line);
}
} else {
System.out.println("Error #2");
}
} catch (Exception e) {
System.out.println("Error #1");
}
}
public void resetList() {
try {
File file = new File("Highscores.txt");
PrintWriter writer;
writer = new PrintWriter(file);
for (int i = 0; i < 5; ++i) {
writer.println("Player name: x - Player score: x ");
}
writer.close();
} catch (Exception e) {
System.out.println("Error #1");
}
}
}
有什么方法可以保存此代码并将其用于此任务?