In: Computer Science
● Write a program that reads words from a text file and displays all the words (duplicates allowed) in ascending alphabetical order. The words must start with a letter. Must use ArrayList.
MY CODE IS INCORRECT PLEASE HELP
THE TEXT FILE CONTAINS THESE WORDS IN THIS FORMAT:
drunk
topography
microwave
accession
impressionist
cascade
payout
schooner
relationship
reprint
drunk
impressionist
schooner
THE WORDS MUST BE PRINTED ON THE ECLIPSE CONSOLE BUT PRINTED OUT ON A TEXT FILE IN ALPHABETICAL ASCENDING ORDER IS PREFERRED
THANK YOU IN ADVANCE
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Collections;
import java.util.List;
public class ArrayListAscending {
public static void main(String[] args) {
try {
File j = new
File("C:\\Users\\NaharaY\\Dropbox\\Jesse -23263\\Introduction to
Software Engineering\\Task 20\\words.txt");
Scanner input =
new Scanner(j);
List<String>list = new ArrayList<String>();
String line =
"";
while(input.hasNext()) {
list.addAll(Arrays.asList(line.split("
")));
}
Collections.sort(list);
for(String
temp:list) {
if(temp!=null &!temp.equals(""))
if(Character.isLetter(temp.charAt(0)))
System.out.println(temp);
}
input.close();
}catch(FileNotFoundException e)
{
System.out.println("Error");
}
}
}
// Please find the required solution
// add required imports for File handling
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
// add required imports for java util
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
//
public class ArrayListAscending {
public static void main(String[] args) {
try {
// create file instance
File words = new File("words.txt");// please update the file path when required
// provide file instance to scanner
Scanner input = new Scanner(words);
// define list
List<String> list = new ArrayList<>();
String line = "";
// add words upon iterating each line
while (input.hasNextLine()) {
line = input.nextLine();
list.addAll(Arrays.asList(line.split(" ")));
}
// print list before sorting
System.out.println("------- List Before Sorting ----------");
System.out.println(list);
// print list after sorting
System.out.println("------- List After Sorting ----------");
Collections.sort(list);
System.out.println(list);
// print list after sorting and starts with letter
System.out.println("------- List After Sorting and starts with letter ----------");
for (String temp : list) {
if (Character.isLetter(temp.charAt(0)))
System.out.println(temp);
}
// finally close the scanner resource
input.close();
} catch (FileNotFoundException e) {
// this exception is caught if the file is not found
System.out.println("Error file not found");
}
}
}
Sample output:
code screenshot: