【发布时间】:2021-06-30 11:05:51
【问题描述】:
标题可能有点误导,但我正在编写一段代码,将其作为文本文件的内容:
04/26/16 Sega 3D Classics Collection 07/14/16 Batman: Arkham Underworld 06/24/16 Tokyo Mirage Sessions #FE
基本上我希望它们按字母顺序排列,它应该创建一个如下所示的全新文件:
Batman: Arkham Underworld Sega 3D Classics Collection Tokyo Mirage Sessions #FE
我尝试使用 indexOf() 方法从我现有的文本文件中仅提取游戏列表的名称。我还尝试将它们存储在一个新数组中以避免计算机混淆。问题是当我尝试将 info 数组的 indexOf 存储到新数组中时,该行给出了“无法从 int 转换为字符串”的错误,我不确定如何修复该错误。
下面是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main (String[]args) throws IOException{
File file = new File("releasedates.txt");
String []arr = input(file);
output(file,arr);
outputSort1(file, arr);
}
public static String[]input (File file) throws FileNotFoundException{
String[]arr = new String[3];
Scanner sc = new Scanner(file);
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextLine();
}
return arr;
}
public static void output(File file, String[] info) throws IOException{
FileWriter writer = new FileWriter("fileName.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByMonth(String[]info){
String temp;
for (int j = 0; j < info.length; j++) {
for (int i = j + 1; i < info.length; i++) {
if (info[i].compareTo(info[j]) < 0) {
temp = info[j];
info[j] = info[i];
info[i] = temp;
}
}
}
}
public static void outputSort1(File file,String[] info) throws IOException{
sortByMonth(info);
FileWriter writer = new FileWriter("fileNameSorted1.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByName(String[]info){
String[] names = new String[3];
for(int i = 0; i < info.length; i ++){
names[i] = info[i].indexOf(" " ,info.length);
}
String temp;
for (int j = 0; j < names.length; j++) {
for (int i = j + 1; i < names.length; i++) {
if (names[i].compareTo(names[j]) < 0) {
temp = names[j];
names[j] = names[i];
names[i] = temp;
}
}
}
}
}
【问题讨论】:
标签: java arrays loops file methods