Searching for a particular line of text in a text file - java

I am having issues with my synonym map. I want to be able to search a text file for a keyword or a related word in the textfile then outputting the found sentence. so my program searches for the answers to questions based on the keyword or sunonym. the way my program works is by searching a text file for a keyword in the question and then outputting the answer to the question which is the next line after then question in the text file. When i search for the main keyword in a question the program works. But when i try to ask a question with the related word the program does not recognize the input. So for example if i enter "how is the major?" the answer to that question is on the next line which is "the major is difficult" but if i enter "how is the focus" the program does not recognize the related word focus Can someone help me find the issue which lies in searching for a related word also. Here is my text file
what is the textbook name?
the textbook name is Java
how is the major?
the major is difficult
how much did the shoes cost?
the shoes cost two dollars
how is the major when cramer took it?
when cramer took it, it was okay
how is the major when jar took it?
jar said it was fine
what is the color of my bag?
the color of my bag is blue
and here is my code
public static class DicEntry {
String key;
String[] syns;
Pattern pattern;
public DicEntry(String key, String... syns) {
this.key = key;
this.syns = syns;
pattern = Pattern.compile(".*(?:"
+ Stream.concat(Stream.of(key), Stream.of(syns))
.map(x -> "\\b" + Pattern.quote(x) + "\\b")
.collect(Collectors.joining("|")) + ").*");
}
}
public static void parseFile(String s) throws IOException {
List<DicEntry> synonymMap = populateSynonymMap(); // populate the map
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
Scanner forget = new Scanner(System.in);
int flag_found = 0;
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
for (DicEntry entry : synonymMap) { // iterate over each word of the
// sentence.
if (entry.pattern.matcher(s).matches()) {
if (lineFromFile.contains(entry.key)) {
//String bat = entry.key;
if(lineFromFile.contains(s)) {
String temp = scanner.nextLine();
System.out.println(temp);
}
}
}
}
}
}
private static List<DicEntry> populateSynonymMap() {
List<DicEntry> responses = new ArrayList<>();
responses.add(new DicEntry("bag", "purse", "black"));
responses.add(new DicEntry("shoe", "heels", "gas"));
responses.add(new DicEntry("major", "discipline", "focus", "study"));
return responses;
}
public static void getinput() throws IOException {
Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
parseFile(input);
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
}

It would seem that after you pass
if (lineFromFile.contains(entry.key))
in your parseFile(String s) method, you would want to know if your user entered input contains any of the entry.syns and replace the synonym with the key
// This is case sensitive
boolean synonymFound = false;
for (String synonym : entry.syns) {
if (s.contains(synonym)) {
s = s.replace(synonym, entry.key)
break;
}
}
Since you want to stop searching once you find a match (exact or synonym match), you'll want to have a return statement to kick out of the method or use a flag to kick out of the while (scanner.hasNextLine())
if (lineFromFile.contains(s)) {
String temp = scanner.nextLine();
System.out.println(temp);
flag_found = 1;
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
// String black = scanner.nextLine();
removedata(temp);
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
// Add return statment to end the search
return;
}
Results:

Related

how to stop a java spell checker program from correcting repetitive words

I've implemented a program that does the following:
scan all of the words in a web page into a string (using jsoup)
Filter out all of the HTML markup and code
Put these words into a spell checking program and offer suggestions
The spell checking program loads a dictionary.txt file into an array and compares the string input to the words inside the dictionary.
My current problem is that when the input contains the same word multiple times, such as "teh program is teh worst", the code will print out
You entered 'teh', did you mean 'the'?
You entered 'teh', did you mean 'the'?
Sometimes a website will have multiple words over and over again and this can become messy.
If it's possible, printing the word along with how many times it was spelled incorrectly would be perfect, but putting a limit to each word being printed once would be good enough.
My program has a handful of methods and two classes, but the spell checking method is below:
Note: the original code contains some 'if' statements that remove punctuation marks but I've removed them for clarity.
static boolean suggestWord;
public static String checkWord(String wordToCheck) {
String wordCheck;
String word = wordToCheck.toLowerCase();
if ((wordCheck = (String) dictionary.get(word)) != null) {
suggestWord = false; // no need to ask for suggestion for a correct
// word.
return wordCheck;
}
// If after all of these checks a word could not be corrected, return as
// a misspelled word.
return word;
}
TEMPORARY EDIT: As requested, the complete code:
Class 1:
public class ParseCleanCheck {
static Hashtable<String, String> dictionary;// To store all the words of the
// dictionary
static boolean suggestWord;// To indicate whether the word is spelled
// correctly or not.
static Scanner urlInput = new Scanner(System.in);
public static String cleanString;
public static String url = "";
public static boolean correct = true;
/**
* PARSER METHOD
*/
public static void PageScanner() throws IOException {
System.out.println("Pick an english website to scan.");
// This do-while loop allows the user to try again after a mistake
do {
try {
System.out.println("Enter a URL, starting with http://");
url = urlInput.nextLine();
// This creates a document out of the HTML on the web page
Document doc = Jsoup.connect(url).get();
// This converts the document into a string to be cleaned
String htmlToClean = doc.toString();
cleanString = Jsoup.clean(htmlToClean, Whitelist.none());
correct = false;
} catch (Exception e) {
System.out.println("Incorrect format for a URL. Please try again.");
}
} while (correct);
}
/**
* SPELL CHECKER METHOD
*/
public static void SpellChecker() throws IOException {
dictionary = new Hashtable<String, String>();
System.out.println("Searching for spelling errors ... ");
try {
// Read and store the words of the dictionary
BufferedReader dictReader = new BufferedReader(new FileReader("dictionary.txt"));
while (dictReader.ready()) {
String dictInput = dictReader.readLine();
String[] dict = dictInput.split("\\s"); // create an array of
// dictionary words
for (int i = 0; i < dict.length; i++) {
// key and value are identical
dictionary.put(dict[i], dict[i]);
}
}
dictReader.close();
String user_text = "";
// Initializing a spelling suggestion object based on probability
SuggestSpelling suggest = new SuggestSpelling("wordprobabilityDatabase.txt");
// get user input for correction
{
user_text = cleanString;
String[] words = user_text.split(" ");
int error = 0;
for (String word : words) {
if(!dictionary.contains(word)) {
checkWord(word);
dictionary.put(word, word);
}
suggestWord = true;
String outputWord = checkWord(word);
if (suggestWord) {
System.out.println("Suggestions for " + word + " are: " + suggest.correct(outputWord) + "\n");
error++;
}
}
if (error == 0) {
System.out.println("No mistakes found");
}
}
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
/**
* METHOD TO SPELL CHECK THE WORDS IN A STRING. IS USED IN SPELL CHECKER
* METHOD THROUGH THE "WORD" STRING
*/
public static String checkWord(String wordToCheck) {
String wordCheck;
String word = wordToCheck.toLowerCase();
if ((wordCheck = (String) dictionary.get(word)) != null) {
suggestWord = false; // no need to ask for suggestion for a correct
// word.
return wordCheck;
}
// If after all of these checks a word could not be corrected, return as
// a misspelled word.
return word;
}
}
There is a second class (SuggestSpelling.java) which holds a probability calculator but that isn't relevant right now, unless you planned on running the code for yourself.
Use a HashSet to detect duplicates -
Set<String> wordSet = new HashSet<>();
And store each word of the input sentence. If any word already exist during inserting into the HashSet, don't call checkWord(String wordToCheck) for that word. Something like this -
String[] words = // split input sentence into words
for(String word: words) {
if(!wordSet.contains(word)) {
checkWord(word);
// do stuff
wordSet.add(word);
}
}
Edit
// ....
{
user_text = cleanString;
String[] words = user_text.split(" ");
Set<String> wordSet = new HashSet<>();
int error = 0;
for (String word : words) {
// wordSet is another data-structure. Its only for duplicates checking, don't mix it with dictionary
if(!wordSet.contains(word)) {
// put all your logic here
wordSet.add(word);
}
}
if (error == 0) {
System.out.println("No mistakes found");
}
}
// ....
You have other bugs as well like you are passing String wordCheck as argument of checkWord and re-declare it inside checkWord() again String wordCheck; which is not right. Please check the other parts as well.

Compare input to a specific line saved in a text file JAVA

In order to validate a country entered by the user, I'm trying to have that country input compared to a list of countries stored in a text file. If the input matches a country stored in the text file, the validCountry would be set to 'true' and the program would be able to proceed.This is what I've got so far:
Scanner sc = new Scanner (System.in);
String country = "";
boolean validCountry = false;
while (!validCountry)
{
System.out.print("Country: ");
String countryIn = sc.next();
try{
Scanner scan = new Scanner(new File("countries.txt"));
while (scan.hasNext()) {
String line = scan.nextLine().toString();
if(line.contains(countryIn))
{
country = line;
validCountry = true;
}
}
}catch(Exception e)
{
System.out.print(e);
}
}
The above simply loops for me to re-input the country (implying that it is invalid).
This is what the countries.txt file looks like (obviously contains all the countries of the world not just the first few starting with 'A' :
Afghanistan
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
...
I'm sure it's a very simple and minor error which I can't seem to find; but I've been trying to detect it for a while but to no avail. I've checked multiple other stackoverflow answers but they didn't seem to work either. I truly appreciate any form of help :)
Please let me know if my question needs further clarification.
I tested the code and it works for me.
I initialized your variable sc like this:
Scanner sc = new Scanner(System.in);
Note that it would be better to load the file outside the while loop (for better performance)
Assuming that in String countryIn = sc.next(); the sc is a scanner that use System.in, change the .next() into nextLine():
String countryIn = sc.nextLine();
then, you should also change if(line.contains(countryIn)) because it will return true even if the given line is a substring of a country (afg will be found in afghanistan even though afg is not in the country list. use equalsIgnoreCase instead:
if (line.equalsIgnoreCase(countryIn)) {
...
}
Try if this class works:
import java.util.Scanner;
import java.io.File;
public class Country {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String country = "";
boolean validCountry = false;
while (!validCountry)
{
System.out.print("Country: ");
String countryIn = sc.nextLine();
try{
Scanner scan = new Scanner(new File("countries.txt"));
while (scan.hasNext()) {
String line = scan.nextLine();
if(line.equalsIgnoreCase(countryIn))
{
country = line;
validCountry = true;
break;
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Problem solved, the countries.txt file I had was encoded in UNICODE. All I had to do was change it to ANSI.

Creating mad-lib game in java and receiving NoSuchElementException method [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to create a java program that recieves a .txt file and plays the game, then prints it all into a new file (named by the user). I've reached the point where all the words have been chosen but am getting a NoSuchElementException message after that. I have a pretty basic knowledge of java and absolutely no clue how to proceed. Anyone have suggestions?
import java.io.*;
import java.util.*;
public class MadLibs {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
//in order to create the output file first prompts user to decide
//whether they want to create a mad-lib, view their mad-lib or quit
//if 'c' is selected then while loop is exited
String action = "c";
String fileName = "fileName";
while (action.equals("c")) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
action = console.nextLine();
action = action.toLowerCase();
File file = new File(fileName);
System.out.print("Input file name: ");
while (!file.exists()) {
fileName = console.nextLine();
file = new File(fileName);
if (!file.exists()) {
System.out.print("File not found. Try again: ");
}
}
//asks for a file to read from for the mad-lib game
//and creates file (named by user) to input the information
System.out.print("Output file name: ");
String outputName = console.nextLine();
System.out.println();
File outputFile = new File(outputName);
PrintStream output = new PrintStream(outputFile);
Scanner tokens = new Scanner(file);
while (tokens.hasNext()) {
String token = tokens.next();
//calls the returned placeHolder
String placeHolder = placeHolder(console, tokens, token);
String newWord = madLib(console, token, placeHolder);
//copies each token and pastes into new output file
}
}
while (action.equals("v")) {
System.out.print("Input file name: ");
fileName = console.nextLine();
File outputFile = new File(fileName);
if (!outputFile.exists()) {
System.out.print("File not found. Try again: ");
fileName = console.nextLine();
} else {
PrintStream output = new PrintStream(outputFile);
output = System.out;
}
}
while (action.equals("q")) {
}
}
public static String madLib(Scanner console, String token, String
placeHolder) throws FileNotFoundException{
String word = placeHolder.replace("<", "").replace(">", ": ").replace("-",
" ");
String startsWith = String.valueOf(word.charAt(0));
if (startsWith.equalsIgnoreCase("a") || startsWith.equalsIgnoreCase("e")
||
startsWith.equalsIgnoreCase("i") || startsWith.equalsIgnoreCase("o")
||
startsWith.equalsIgnoreCase("u")) {
String article = "an ";
System.out.print("Please type " + article + word);
String newWord = console.next();
return newWord;
} else {
String article = "a ";
System.out.print("Please type " + article + word);
String newWord = console.next();
return newWord;
}
}
public static String placeHolder(Scanner console, Scanner tokens, String
token) throws FileNotFoundException {
while(!(token.startsWith("<") && token.endsWith(">"))) {
//not a placeholder!
//continue reading file
token = tokens.next();
}
//outside of this while loop = found a placeholder!!
String placeHolder = token;
//returns placeholder to main
return placeHolder;
}
//method prints out the introduction to the game
public static void intro() {
System.out.println("Welcome to the game of Mad Libs");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
System.out.println();
}
}
Also am currently using a file called simple.txt with the text:
I wannabe a <job> when I grow up.
Just like my dad.
Life is <adjective> like that!
This is the full error message:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at MadLibs.placeHolder(MadLibs.java:96)
at MadLibs.main(MadLibs.java:46)
I ran your code and got a NoSuchElementException instead of a NoSuchFileException. To circumvent this exception you need to check if there are any more tokens while in the method placeHolder. Otherwise, after entering every placeholder you would still search for the next placeholder token although there is no next().
Change your code to:
while(tokens.hasNext() && !(token.startsWith("<") && token.endsWith(">"))) {
//not a placeholder!
//continue reading file
System.out.println(token);
token = tokens.next();
}

Searching for a string in a text file using Java

I am trying to make the user input an Airport Name, and the program will search from a text file to get the matching Code, right now I only need it to read the line. I have looked into many similar questions in here, but nothing works for me. The program return the else result rather than the found result.
This is my code so far
public static void main (String[] args) throws IOException
{
File file = new File("codes01.dat");
Scanner myFile = new Scanner(file);
Scanner kb = new Scanner(System.in);
String line;
System.out.println("Hey man, this is totally leigt, just enter an Airport code and I'll hook you up.");
System.out.print("First, y'all need to give me the file name: ");
String fileName = kb.nextLine();
if (fileName.equalsIgnoreCase("codes01"))
{
System.out.print("Cool, now give me your Airport Name: ");
String AirportName = kb.nextLine();
while (myFile.hasNextLine())
{
line = myFile.nextLine();
String name = myFile.next();
System.out.println(line);
if(name.equalsIgnoreCase(AirportName))
{
System.out.println("IT'S WORKING, I DON'T KNOW HOW BUT IT IS "+line);
break;
}
else
{
System.out.println("Sorry, dude, ain't no airport in my VERY limited list with that name");
break;
}
}
}
The program return the else result rather than the found result.
That is because you are breaking out of the loop after testing the first line in your file.
Look carefully at your code ... in context.
if(name.equalsIgnoreCase(AirportName)) {
System.out.println("It is working");
break;
} else {
System.out.println("Sorry");
break; // What????
}
Why are you using the break statement in the if-else block? Try to get rid of the break statement and then execute your code.
if(name.equalsIgnoreCase(AirportName))
{
System.out.println("The name of Airport matches");
}
else
{
System.out.println("Sorry No Match Found");
}
Look closely at these two lines. There's a problem there. Step through the code in your head pretending you are the Scanner class.
line = myFile.nextLine();
String name = myFile.next();

Search modify and delete from text file

I'm trying to make a method search, edit and/or delete a specific word in a text file
private void modifyShow() throws FileNotFoundException, IOException {
Scanner input = new Scanner(System.in);
System.out.println("Please search for a TV Show\nExample: Simpsons");
String tvSearch = input.nextLine();
System.out.println("Displaying results for: " + tvSearch);
String searchTerm = tvSearch;
searchTerm = searchTerm.toLowerCase();
int count = 0;
Scanner show = new Scanner(new File("src/TVShows.txt"));
while (show.hasNext()) {// loop
if (show.equals(searchTerm)) { // find
System.out.println(show);// display
}
}
}
So it doesn't actually search the file but it opens it I believe but the while statement is throwing it off. So once it finds the word it needs to print say
System.out.println("Enter a new name for " + tvSearch + ".");
And have an input for the show and then replace it.
Replace your if (show.equals(searchTerm)) with if (show.next().equals(searchTerm)),the search would work.You were actually comparing a Scanner object with the String.

Categories