So I am writing some code that takes an unsorted file and writes out only the names of the games in a new file in alphabetical order.
This is what the original file looks like:
04/26/16 Sega 3D Classics Collection 07/14/16 Batman: Arkham Underworld 06/24/16 Tokyo Mirage Sessions #FE
This is the desired contents of the new file
Batman: Arkham Underworld Sega 3D Classics Collection Tokyo Mirage Sessions #FE
The problem with my code that it for some reason takes out the first word and sorts it. (for example instead of Batman: Arkham Underworld it would be Arkahm Underworld ).What I have tried is to subtract 1 from the indexOf(" ") and the info.length of my method but that did not seem to work. I know for sure that the method and the writing of the files work but the first word is missing ad will sort with the string without the first word. I'm not quite sure where the problem is with this code
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("C:/Users/cyrus/Downloads/Lab 11/releasedates.txt"); String[] arr = input(file); sortByName(arr); } public static void sortByName(String[] info) throws IOException { String[] names = new String[3]; for (int i = 0; i < info.length; i++) { names[i] = info[i].substring(info[i].indexOf(" "), info[i].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; } } } FileWriter writer = new FileWriter("SortedByName.txt"); for (String aString : names) { writer.write(aString); } writer.close(); } }
https://stackoverflow.com/questions/66947757/sorted-text-file-array-missing-words-java April 05, 2021 at 10:58AM
没有评论:
发表评论