HELP IN JAVA: This exercise uses the Java LinkedList class. Using the input file
ID: 3880481 • Letter: H
Question
HELP IN JAVA:
This exercise uses the Java LinkedList class.
Using the input file words_no_duplicates.txt, input each string putting it into a different LinkedList depending on the first character in the String. (Yes, you will need 26 linked lists).
Then prompt the user for a (lower case) character and display all the words beginning with that character. (If the user enters an invalid character, trap them in a loop until they give you a valid one).
Note: nothing is sorted.
words_no_duplicates.txt:
noncollectable
reallocation
drenching
obnoxious
venality
dybbuk
shotgun
changelessly
handiwork
unheralded
dovecote
anode
spellbind
psychologist
improvisational
prejudiced
Explanation / Answer
Below is your program. Please place your text file in project folder or change the fileName atribute with the absolute address of the file to avoid FileNotFoundException. Let me know if you have any issues running this....
WordsInLList.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class WordsInLList {
public static void main(String[] args) {
LinkedList<String>[] lists = new LinkedList[26];
for (int i = 0; i < lists.length; i++) {
lists[i] = new LinkedList<>();
}
String fileName = "words_no_duplicates.txt";
Scanner sc = new Scanner(System.in);
try {
readFile(fileName, lists);
boolean done = false;
while (!done) {
System.out.print("Please enter a lower case character from a-z: ");
Character c = sc.next().charAt(0);
int ascii = (int) c;
if (ascii >= 97 && ascii <= 122) {
ascii = ascii - 97;
System.out.print("Words starting from " + c + " are: " + Arrays.toString(lists[ascii].toArray()));
done = true;
} else {
System.out.println("Please enter a valid character...");
done = false;
}
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Please check the location of the file.");
}
}
private static void readFile(String fileName, LinkedList<String>[] lists) throws FileNotFoundException {
Scanner in = new Scanner(new File(fileName));
String word;
Character firstChar;
int offset;
while (in.hasNextLine()) {
word = in.nextLine();
firstChar = word.charAt(0);
offset = (int) firstChar - 97;
lists[offset].add(word);
}
}
}
Sample Run:-
Please enter a lower case character from a-z: 3
Please enter a valid character...
Please enter a lower case character from a-z: .
Please enter a valid character...
Please enter a lower case character from a-z: p
Words starting from p are: [psychologist, prejudiced]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.