【发布时间】:2015-11-19 07:00:19
【问题描述】:
为您提供以下列表,其中包含现代历史的(半随机)年份。将列表保存到名为“events.txt”的文本文件中编写一个程序:
- 读取文件“events.txt”
- 先按最新事件排序
- 确定 1892 年 CMU 的成立是否被视为世界历史事件
- 如果还没有,将事件添加到事件列表中
- 将新的事件列表写入名为“sorted_events.txt”的文件
import java.io.*;
import java.util.*;
public class EventSorter {
public static void main(String[] args) throws FileNotFoundException{
File file =new File("events.txt");
FileReader read = new FileReader(file);
LineNumberReader lines = new LineNumberReader(read);
Scanner readIn = new Scanner(file);
PrintWriter output = new PrintWriter("sorted_events.txt");
try{
//call for the file
//make sure it exists
if(file.exists()){
{
//first write this to determine the number of lines
int lineNumber = 0;
//gets the number of lines
while (lines.readLine() != null){
lineNumber++;
}
int[] event = new int[lineNumber];
int j = 0;
while(readIn.hasNext()){
event[j]=readIn.nextInt();
j++;
}
//sort the array
Arrays.sort(event);
boolean found;
for(int i = 0; i < event.length; i++){
if (event[i] == 1892){
//see if 1892 is on the list
System.out.println("CMU is a historic event");
found = true;
}
else{
addElement(event, 1892);
}
}
int[] sortedEvent = new int[lineNumber];
for(int k = 0; k < event.length; k++){
sortedEvent[k] = event[(event.length-1) - k];
System.out.println(sortedEvent[k]);
}
for(int print = 0 ; print < event.length; print++){
output.println(sortedEvent[print]);
}
}
readIn.close();
output.close();
lines.close();
}else{
System.out.println("File does not exist!");
}
}
catch(IOException e){
e.printStackTrace();
}
}
static int[] addElement(int[] a, int e) {
a = Arrays.copyOf(a, a.length + 1);
a[a.length - 1] = e;
return a;
}
}
【问题讨论】:
-
你是从考试中复制的还是什么?
-
不,这是一个家庭作业,我不知道该怎么做我不知道如何将元素 1892 添加到新的排序 txt 文件中
-
现在我看着它,它看起来像是我这样做了,但是知道,我复制了作业的说明,所以你可以看到我猜想我在做什么。
-
您的实际问题是什么?