I am trying to work on a code for extra credit in my Programming class. The question asks for the user to input a text file, and display all the words in that file(including duplicates) in ascending order. After writing the code several different times over the course of four days, I have finally gotten it to accept the file and display the output. However, instead of displaying the words fromt the file, it displays a bunch of symbols. Here is a sample of the output: £5Z;•_=QÉ? #Û=¸2?±.
It displays a long list of similar stuff. I've tried revising the code and I either get error messages, or it just displays symbols instead of words. Please help! I only have until 8 tonight to submit it online!(Even though I know DaniWeb isn't meant for help on homework problems, but I'm stumped)
import java.io.*;//imports all Input/Output methods
import java.util.*;//imports all utility methods
public class Assessment3 {
public static void main(String[] args) throws IOException {
//use IOException
Scanner input = new Scanner(System.in); //calls Scanner to allow for input
System.out.println("Enter a text file for sorting its words in alphabetical order." + "\n Note! You must input the ENTIRE FILE LOCATION." + "\n Example: C:/Users/Username/File Location/Filename.file type." );
String text = input.nextLine();
File file = new File(text); //creates a file from the user input
if (!file.exists()) { //creates a loop to display a message if the file does not exist
System.out.println("The input file you specified either does not exist or is not in the designated location.");
}
BufferedReader charRead = null; //creates an empty BufferReader to read all characters, strings or arrays from a file
List<String> words = new ArrayList<String>(); //creates an ArrayList which will be uses to store a string of words from the file
try {
charRead = new BufferedReader(new FileReader(text)); //assigns new BufferReader to charWord, as BufferReader uses FileReader to read the input file
String nextSentence = charRead.readLine(); //reads every line of the sentence
while (nextSentence != null) {
String[] allWords = nextSentence.split(" "); //adds all words from the document to array, separating them with a space
nextSentence = charRead.readLine(); //reads the next line from the file and replaces previous nextSentence
words.add(nextSentence); //assigns all words to ArrayList
}
charRead.close();//exits the BufferReader
}
catch (IOException e) {
e.printStackTrace();
}
display(words);
}
public static<E> void display(List<E> wordList) {
for (int i = 0; i < wordList.size(); i++) {
System.out.println(wordList.get(i));
}
}
}