Need help writing a method that reads an input file that seperate all the words
ID: 3890486 • Letter: N
Question
Need help writing a method that reads an input file that seperate all the words from the .txt file. That is, any symbol (period, comma, backslash, number...) anything other than a string of words should be removed and the words should be placed in a String array...
HELPFUL INFO: The input file that is being read from is a block of java code...so as good test data for you, I have provided a piece of the text that will be read
----------------------------------------------------------------------------------------------------------------------------
TEST FILE to USE FOR THIS EXAMPLE
------------------------------------------------------------------------------------------------------------------
Explanation / Answer
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.io.File;
import java.io.FileNotFoundException;
class Main {
public static void main(String args[]) {
Scanner sc = null;
//pattern for finding only alphabets
Pattern pattern = Pattern.compile("[^\p{Alpha}']+");
String str;
File file = new File("file.txt");
//Dynamic list to store words
List < String > list = new ArrayList < String > ();
try {
//open file using scanner
sc = new Scanner(file);
} catch (FileNotFoundException e) {
// if unable to open file catch the exception
System.out.println("File not found");
}
//using while to read till scanner has elements
while (sc.hasNext()) {
// tokenize the file based on pattern
sc.useDelimiter(pattern);
//get the next element from scanner
str = sc.next();
System.out.println(str);
// if element is not empty add it to list
if (!str.equals("")) {
list.add(str);
}
}
}
}
/*
file.txt
Container c = getContentPane();
c.setLayout(new GridLayout(2,1));
c.setBackground(Color.white);
sample output
Container
c
getContentPane
c
setLayout
new
GridLayout
c
setBackground
Color
white
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.