Java How to search a word from text file [closed] - java

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 6 years ago.
Improve this question
edit: Write a program to read in 100 words from a file. Then, have the user search for a word until they enter 'quit'.
The program will read in up to 100 words from a file. The file may or may not contain 100 words but the array should hold up to 100 (if the list does not contain enough words, fill the rest of the array with empty strings).
After the file is read in, the program will prompt the user for a search string. The program will then search for the string and tell the user if the word was found or not. The program will continue to get search strings from the user until the user enters 'quit'
Hello I need help write a program to find a word from text file
the result should look like:
Enter a word to search for: taco
Word 'taco' was found.
Enter a word to search for: asd
Word 'asd' was NOT found.
and when user enter the word "quit" the program will quit
below is what I have so far and need help to complete
import java.io.*;
import java.util.Scanner;
public class project2 {
public static void main( String[] args ) throws IOException {
String[] list;
String search;
list = load_list( "words.txt" );
search = prompt_user( "\nEnter a word to search for: " );
while ( ! search.equals( "quit" ) ) {
System.out.println( "Word '" + search + "' was" +
( ( find_word( search, list ) ) ? "" : " NOT" ) +
" found." );
search = prompt_user( "\nEnter a word to search for: " );
}
System.out.println();
}

for(String s: list){
if(s.equals(search)){
//do whatever
}
}

Use this:
Scanner txtscan = new Scanner(new File("filename.txt"));
while(txtscan.hasNextLine()){
String str = txtscan.nextLine();
if(str.indexOf("word") != -1){
System.out.println("EXISTS");
}
}

The below code answers this question perfectly:
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("newFile.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
if(line.indexOf(word) != -1)
{
System.out.println("Word EXISTS in the file");
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
if(val == 0)
{
System.out.println("Word does not exist");
}
System.out.println("-------continue or quit--- enter continue or quit");
word = input.next();
}

Related

How do I return the number of items found after I do a search?

Please help me to figure out how I can get a count of the result when I do a search against a specific folder?
Also how can I ask the user if they want to perform another search?
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
}
}
}
}
If you want to count your matches you can do the following
int i=0;
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
i++;
}
}
System.out.println("Total number of results: " + i);`
As for asking the user, consider using a do-while loop in the following format
do{
// your code
// ask user and read his answer on a string called userChoice
}while (userChoice.equals('y'))
Experiment with our suggestions and you will find the answer easily enough!
I would add a variable
int count = 0;
right before the for loop, and just increment it if it's a match.
This should get you started. I am incrementing the variable count each time a match is found. I am also looping forever so it keeps asking the user for more input.
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
while(true){
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
int count=0;
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
count++;
}
}
}
}
}
Use a while loop and prompt the user to enter a phrase (such as 'exit') if they want to stop. After reading the user input, check the phrase and call a break if it matches the exit phrase.
Use a variable as Robert suggested to count the total number of files found.

Counter Occurrences of User Specified String in a Text File

Count keeps coming up zero. I'm just trying to read the text file and look for the word, and display the count back to the user.
I'm not sure where it's falling apart. The If statement I think, but not sure where the syntax is going wrong. Thanks for any help!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import javax.swing.*;
public class TextSearchFromFile
{
public static void main(String[] args) throws FileNotFoundException
{
boolean run = true;
int count = 0;
//greet user
JOptionPane.showMessageDialog(null,
"Hello, today you will be searching through a text file on the harddrive. \n"
+ "The Text File is a 300 page fantasy manuscript written by: Adam\n"
+ "This exercise was intended to have the user enter the file, but since \n"
+ "you, the user, don't know which file the text to search is that is a \n"
+ "bit difficult.\n\n"
+ "On the next window you will be prompted to enter a string of characters.\n"
+ "Feel free to enter that string and see if it is somewhere in 300 pages\n"
+ "and 102,133 words. Have fun.",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
while (run)
{
try
{
//open the file
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
//prompt user for word
CharSequence findWord = JOptionPane.showInputDialog(null,
"Enter the word to search for:",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
count = 0;
while (scanner.hasNext())
{
if ((scanner.next()).contains(findWord))
{
count++;
}
} //end search loop
//output results to user
JOptionPane.showMessageDialog(null,
"The results of your search are as follows: \n"
+ "Your String: " + findWord + "\n"
+ "Was found: " + count + " times.\n"
+ "Within the file: An Ever Throne Tale 1.txt",
"Text Search",
JOptionPane.PLAIN_MESSAGE);
} //end try
catch (NullPointerException e)
{
JOptionPane.showMessageDialog(null,
"Thank you for using the Text Search.",
"Text Search",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} //end run loop
} // end main
} // end class
EDIT:
Need help again. The instructor changed the parameters of the project and now I need to find word fragments like "th" or "en" and count those as well.
This I feel is beyond what he has taught and I have no idea how to make that work. I've googled until I can't google anymore.
You have to provide a File Object to Scanner in order to read the file, currently everything is getting searched in a String "An Everthrone Tale 1.txt"
Scanner scanner = new Scanner(new File("An Everthrone Tale 1.txt"));
And for searching a word, you need to do like this:
while (scanner.hasNext())
{
if (findWord.equals(scanner.next()))
{
count++;
}
}
and if you want to perform case-insensitive search then use String#equalsIgnoreCase instead of String#equals
Hope this helps

Why does the compiler complain "while expected" when I try to add more code?

Write a program with a word containing # character as an input. If the word doesn't contain #, it should prompt the user for a word with #. Once a word with # is read, it should output the word then terminate.
This is what I have done so far:
public class find {
public static void main(String[] args) {
System.out.println(" Please enter a word with # ");
Scanner scan = new Scanner(System.in);
String bad = "#";
String word = scan.next();
do
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
while (!word.contains(bad));
}
}
I can get it to terminate after a word containing "#" is given as input, but if I try to add a Scanner to the line after "please try again", it says while expected.
I think issue is you are missing surrounding braces for do/while:
do
if (!word.contains( bad ))
System.out.println( " Please try again " );
else
System.out.println( " " + word);
while ( !word.contains( bad ));
should be:
do
{
if (!word.contains( bad ))
System.out.println( " Please try again " );
else
System.out.println( " " + word);
}while ( !word.contains( bad ));
Some people may not like this, but my suggestion is always use open/close braces. In this case, for the code if/else also. It avoids lot of confusion.
This is where your problem lies:
do
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
while (!word.contains(bad));
You need to put braces from where the loop starts until it ends. |So this thing should like:
do {
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
} while(!word.contains(bad));
For Better Practice You should Check do...while loops here.
The problem with your code is it is not re-reading the word in your loop.
Modify your loop like this (minimum change to your code).
do {
word = scan.next();
if (!word.contains(bad))
System.out.println(" Please try again ");
else
System.out.println(" " + word);
}
while (!word.contains(bad));
And yes as others have pointed out try to use braces especially with nested constructs.
There are two issues.
Your code is not using the braces properly
you are not attempting to read the new word if right word is not entered.
Also I prefer while loop better in the case as opposed to do-while loop as below.
Scanner scan = new Scanner ( System.in );
String required= "#";
System.out.println( " Please enter a word with # " );
String word = scan.next() ;
//check if the right word(containing #) is entered,
//if not then loop until it is enteres
while((!word.contains(required)){
System.out.println( " Please try again " );
//read the new word as input from the user
word = scan.next() ;
}
//right word is entered, display it
System.out.println(word);
Also please note that when you use scan.next(), it reads each word separately if entered in the same line.

How do sort my pattern match results as complete match, half a match and so on [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Regular expression not matching subwords in phrase
My program displays the matching results, but I want to sort the results as complete match (100%), half a match and so on.
My text file contains the following line:
Red car
Red
Car
So If I search for: “red car”. I get the following results
Red car
Red
Car
So what I want to do is to sort the found results as follows:
"red car" 100% match
"red" 40% match
"car" 40% match
Any help is appreciated.
Any help is appreciated. My code is as follows:
public static void main(String[] args) {
// TODO code application logic here
String strLine;
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:\\textfile.txt"");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Scanner input = new Scanner (System.in);
System.out.print("Enter Your Search: "); // String key="red or yellow";
String key = input.nextLine();
while ((strLine = br.readLine()) != null) {
Pattern p = Pattern.compile(key); // regex pattern to search for
Matcher m = p.matcher(strLine); // src of text to search
boolean b = false;
while(b = m.find()) {
System.out.println( " " + m.group()); // returns index and match
// Print the content on the console
}
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
Assuming you are searching for "Red" or "Yellow", and or is the only logical operator you need (no 'and' or 'xor') and you don't want to use any wildcards or regular-expressions in what you search for, then I would simply loop through, trying to match each String in turn against the line. In pseudo-code, something like:
foreach (thisLine: allLinesInTheFile) {
numOfCharsMatching = 0
foreach (thisString: allSearchStrings) {
if (thisLine.contains(thisString) {
numOfCharsMatching = numOfCharsMatching + thisString.length
}
}
score = ( numOfCharsMatching / thisLine.length ) * 100
}
If you don't want spaces to count in your score, then you'd need to remove them from the thisString.length (and not allow them in your search terms)
One other problem is the numOfCharsMatching will be incorrect if matches can overlap (i.e. if searching for 'row' or 'brown' in 'brown row' it will say that there are 11 characters matching, longer than the length of the string. You could use a BitSet to track which characters have been involved in a match, something like:
foreach (thisLine: allLinesInTheFile) {
whichCharsMatch = new BitSet()
foreach (thisString: allSearchStrings) {
if (thisLine.contains(thisString) {
whichCharsMatch.set(startPositionOfMatch, endPositionOfMatch, true)
}
}
score = ( numOfCharsMatching / thisLine.length ) * 100
}
Have a look at the BitSet javadoc, particularly the set and cardinality methods

Java: 2 runtime errors I can't figure out

I am working on a homework assignment, and I am going a little "above and beyond" what is called for by the assignment. I am getting a run-time error in my code, and can not for the life of me figure out what it is that I have done wrong.
Here is the assignment:
Write a program that displays a simulated paycheck. The program should ask the user to enter the date, the payee’s name, and the amount of the check. It should then display a simulated check with the dollar amount spelled out.
Here is my code:
CheckWriter:
/* CheckWriter.java */
// Imported Dependencies
import java.util.InputMismatchException;
import java.util.Scanner;
public class CheckWriter {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
// Try to get the name
String name = "";
NameValidator validateName = new NameValidator();
while (validateName.validate(name) == false) {
System.out.println("Enter the name: ");
name = keyboard.nextLine();
if (validateName.validate(name) == false) {
System.out.println("Not a valid name.");
}
}
// Get the date
String date = "";
DateValidator validateDate = new DateValidator();
while (!validateDate.validate(date)) {
System.out.println("Enter the date (dd/mm/yyyy): ");
date = keyboard.nextLine();
if (!validateDate.validate(date)) {
System.out.println("Not a valid date.");
}
}
// Try to get the amount of the check
String checkAmount = "";
CurrencyValidator validateCurrency = new CurrencyValidator();
while (!validateCurrency.validate(checkAmount)) {
System.out.print("Enter the Check Amount (XX.XX): $");
checkAmount = keyboard.nextLine();
if (!validateCurrency.validate(checkAmount)) {
System.out.println("Not a valid check amount.");
}
}
String checkWords = checkToWords(checkAmount); // ERROR! (48)
System.out
.println("------------------------------------------------------\n"
+ "Date: "
+ date
+ "\n"
+ "Pay to the Order of: "
+ name
+ " $"
+ checkAmount
+ "\n"
+ checkWords
+ "\n"
+ "------------------------------------------------------\n");
}
private static String checkToWords(String checkAmount) {
/**
* Here I will use the string.split() method to separate out
* the integer and decimal portions of the checkAmount.
*/
String delimiter = "\\.\\$";
/* Remove any commas from checkAmount */
checkAmount.replace(",", "");
/* Split the checkAmount string into an array */
String[] splitAmount = checkAmount.split(delimiter);
/* Convert the integer portion of checkAmount to words */
NumberToWords intToWord = new NumberToWords();
long intPortion = Long.parseLong(splitAmount[0]); // ERROR! (84)
intToWord.convert(intPortion);
String intAmount = intToWord.getString() + " dollars";
/* Convert the decimal portion of checkAmount to words */
String decAmount = "";
long decPortion = Long.parseLong(splitAmount[1]);
if (decPortion != 0) {
NumberToWords decToWord = new NumberToWords();
decToWord.convert(Long.parseLong(splitAmount[1]));
decAmount = " and " + decToWord.getString() + " cents.";
}
return (intAmount + decAmount);
}
}
Note that I am using external class files to handle validation of the name, date, currency, and conversion from numbers to words. These class files all work as intended.
The error I am getting is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at CheckWriter.checkToWords(CheckWriter.java:82)
at CheckWriter.main(CheckWriter.java:46)
I have commented the lines in my code that are causing the errors that I am experiencing.
Could someone please assist me in figuring where my code is going wrong? I can include the other class files if you feel that it would be needed.
EDIT: When I run the code, it asks for the name and date. Before asking for the check amount is when it throws the error.
EDIT 2: A huge thank you to cotton.m! Thanks to his advice, I have changed the while statements to look like this:
while(!validateDate.validate(date) && date == "")
This has now fixed my issue. It would appear that when validating data with a regex expression, an empty string will return true.
The String you are trying to parse in an empty length string.
My suggestion would be to
1) Check the value of checkAmount at the start of checkToWords - if it is blank there's your problem
2) Don't do that split. Just replace the $ like you did the , (I think this is your real problem)
Also you are going to have another issue in that 10000.00 is not a long. I see you are splitting out the . but is that really what you want?
It is NumberFormatException, the value in checkAmount (method parameter) is not a valid Number.
You need to set checkAmount=checkAmount.replace(",", "");
Otherwise checkAmount will still have , inside and causes NumberFormatExcpetion.
Your issue is with your delimiter regex, currently you are using \.\$ which will split on a literal . followed by a literal $. I'm assuming that what you are actually intending to do is to split on either a . or a $, so change your delimiter to one of the following:
String delimiter = "\\.|\\$"
or
String delimiter = "[\\.\\$]"
As your code is now, checkAmount.split(delimiter) is not actually successfully splitting the string anywhere, so Long.parseLong(splitAmount[0]) is equivalent to Long.parseLong(checkAmount).
It should be:
String delimiter = "[\\.\\$]";
and then you have to check that splitWord[i] is not empty.

Categories