[英]Java : How do I print an ascending column and next to that column the same set of integers except in descending order all in one single text file
I need some help in how to do a certain step as I can not seem to figure it out. 我似乎无法弄清楚如何执行某个步骤需要一些帮助。 I was given a text file with 100 numbers in it all random, I am supposed to sort them either in ascending order, descending order, or both depending on the user input. 我给了一个文本文件,里面有100个数字,它们都是随机的,我应该根据用户的输入对它们进行升序,降序或两者排序。 Then which ever the user inputs the set of integers will be sorted and printed in a text file. 然后,用户输入的整数集将被排序并打印在文本文件中。 I am having trouble printing the both file. 我无法同时打印两个文件。 Here is my code up until the both statement. 这是我的代码,直到both语句为止。
public static void print(ArrayList<Integer> output, String destination){
try {
PrintWriter print = new PrintWriter(destination);
for(int i = 0; i < output.size(); i++){
print.print(output.get(i) + " ");
}
print.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
BufferedReader br = null;
ArrayList<Integer> words = new ArrayList<>();
BufferedReader reader;
String numbers;
try {
reader = new BufferedReader(new FileReader("input.txt"));
while((numbers = reader.readLine()) != null)
{
words.add(Integer.parseInt(numbers));
}
System.out.println("How would you like to sort?");
System.out.println("Please enter asc(For Ascending), desc(For Decending), or both");
String answer = input.next();
Collections.sort(words);
if(answer.equals("asc")){
Collections.sort(words);
System.out.println(words);
print(words,"asc.txt");
}
else if(answer.equals("desc")){
Collections.reverse(words);
System.out.println(words);
print(words,"desc.txt");
When I type in "both" the text file that is created only has one column set of integers that is going in descending order, not both and I have no idea how to print both sets. 当我键入“两个”时,创建的文本文件只有一列整数集,它们以降序排列,而不是两个都一样,而且我也不知道如何打印这两个集合。 If someone could shed some light I would really appreciate it. 如果有人能阐明一些想法,我将非常感激。
else if(answer.equals("both")){
System.out.println(words);
print(words,"both.txt");
Collections.reverse(words);
System.out.println(words);
print(words,"both.txt");
You need to use FileOutputStreams#Constructor where you can pass a boolean value to tell whether to append to my file or not. 您需要使用FileOutputStreams#Constructor ,您可以在其中传递一个布尔值来告诉是否要附加到我的文件中。
So use like this: 所以这样使用:
PrintWriter print = new PrintWriter(new FileOutputStream(destination, true));
/\
||
||
To append to the file
From JavaDocs 从JavaDocs
public FileOutputStream(File file,
boolean append)
throws FileNotFoundException
Parameters: 参数:
file - the file to be opened for writing. file-要打开以进行写入的文件。
append - if true, then bytes will be written to the end of the file rather than the beginning append-如果为true,则字节将被写入文件的末尾而不是开头
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.