Having trouble searching a text file for strings - java

So I'm attempting to simulate a very basic search engine by reading a text file filled with data and then have a user search the file using some keywords, and then whichever "websites" contained in the text file that contain that keyword are returned back to the user. My code so far can read the text file (as far as I know), however no matter the entered keyword, the console almost always states that no results can be found (the text file doesn't contain the keyword(s). Thanks everyone.
Here's the appropriate code:
package myquery;
import java.util.Scanner;
import java.util.*;
import java.io.*;
public class MyQuery{
public static void main(String[] args){
Hashtable<String, ArrayList<String> > hash = new Hashtable<String, ArrayList<String> >();
Scanner input = new Scanner(System.in);
System.out.println("Here is where your .txt file(s) should be located for this program to work properly:");
System.out.println(new java.io.File("").getAbsolutePath());
System.out.println("\nEnter the filename that you want to Search values for. For example \"MyQuery.txt\"");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(input.nextLine()));
System.out.println("The file was found :) Here are the contents:");
while(reader.ready())
{
String currentline = reader.readLine();
String[] result = currentline.split("\\s");
for(int i = 0; i < result.length; i++)
{
if(!hash.containsKey(result[i]))
{
ArrayList<String> temp = new ArrayList<String>(1);
temp.add(currentline);
hash.put(result[i], temp);
}
else
{
ArrayList<String> temp = (ArrayList<String>)hash.get(result[i]);//
temp.add(currentline);
}
}
}
}
catch(Exception e)
{
System.out.println("Your file was not found unfortunately. Please try again.");
System.exit(1);
}
System.out.println(hash);
do
{
System.out.println("Enter a key to search for the value it is associated with.\n");
System.out.println(hash.get(input.nextLine()));
System.out.println("\nWant to try again? If so, press return and then follow the prompt. Type \"-1\" to quit");
}
while(!input.nextLine().equals("-1"));
try
{
reader.close();
}
catch(Exception e)
{
System.out.println(e);
System.exit(1);
}
}
}
And an example of one line in the text file:
www.Mets.com, "The New York Mets", baseball, team, NY
Here's an example of how the program should respond:
Enter a key to search for the value it is associated with.
Mets
www.Mets.com The New York Mets
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
But here's what I'm getting instead:
Enter a key to search for the value it is associated with:
Mets
null
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
ALTHOUGH. If I enter a word that matches any word besides the first/last ones, it works.
For example
Enter a key to search for the value it is associated with:
New
[www.Mets.com, "The New York Mets", baseball, team, NY, www.nytimes.com, "The New York Times", news]
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit

Related

same input calling two different methods in java

I'm trying to implement the main method in java for a KWIC. The issue I'm having is that I have to ask the user if they want to write the input from the console/file and write the output to the console/file. The first time asking the user for console/file works fine when I have to read, but when I ask them again for the output I believe it goes back into the first If condition. Here is the code for reference.
try {
System.out.println("Please enter FILE to input from file or CONSOLE to input from console:");
String userInput = "";
while ((userInput = scannerWrapper.nextLine()) != "-1") {
if (userInput.equals("CONSOLE")) {
System.out.println("Please enter FILE to output from file or CONSOLE to output from console:");
List<String> cshiftConsole = circularShifter.shiftLines(inputFromConsole.read());
if (userInput.equals("CONSOLE")) {
System.out.println("Please enter lines to add, then enter -1 to finish:");
// Console
cshiftConsole = alphabetizer.sort(cshiftConsole);
outputToConsole.write(cshiftConsole);
for (String element : cshiftConsole) {
System.out.println(element);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
This is my console output
Please enter FILE to input from file or CONSOLE to input from console:
CONSOLE
Please enter FILE to output from file or CONSOLE to output from console:
CONSOLE
Software Architecture
-1
Please enter lines to add, then enter -1 to finish:
Architecture Software
CONSOLE
Software Architecture
After the second CONSOLE(userInput) I should be asked to enter the lines, But this is taking CONSOLE as the input I want to circularly shift. Any help would be great thank you.
You have some issues in your code, and if I understand correctly you want to decide where to INPUT from, where to OUTPUT to and get a couple of Strings into a List.
(userInput = scannerWrapper.nextLine()) != "-1" You compare Strings in Java using .equals(...) as you did in your code further below.
Every time you're asking your user where he wants to input from, you just have to read it once, so instead of having it inside a while do it on an if.
You create your list on every iteration, have it as an instance member instead.
On every iteration you're printing your objects, wait until the user stops adding items first (they type -1)
A better approach could be like this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class InputCycle {
private Scanner scanner;
private static final String CONSOLE = "CONSOLE";
private static final String EXIT_CODE = "-1";
private List<String> list;
public static void main(String[] args) {
new InputCycle().readAndWrite();
}
private void readAndWrite() {
scanner = new Scanner(System.in);
list = new ArrayList<String>();
System.out.println("INPUT FROM CONSOLE / FILE");
String input = scanner.nextLine(); // Read where to input from
if (input.equals(CONSOLE)) {
System.out.println("OUTPUT TO CONSOLE / FILE");
String output = scanner.nextLine(); // Read where to output to
if (output.equals(CONSOLE)) {
System.out.println("WRITE LINES (" + EXIT_CODE + " TO EXIT)");
String line = "";
do {
line = scanner.nextLine(); // Read every line
if (!line.equals(EXIT_CODE)) {
list.add(line);
}
} while (!line.equals(EXIT_CODE));
} else { // Write to a file with your own code
System.out.println("Writing to a file");
}
} else { //Read from a file
System.out.println("Reading from a file");
}
System.out.println("ALL LINES: ");
list.forEach(line -> System.out.println(line)); //Print all the lines user wrote
}
}
That has this output:
INPUT FROM CONSOLE / FILE
CONSOLE
OUTPUT TO CONSOLE / FILE
CONSOLE
WRITE LINES (-1 TO EXIT)
FOO
BAR
BANANA
-1
ALL LINES:
FOO
BAR
BANANA

How can I compare an integer and a file name?

I am trying to make a login/password program which asks if you have an account and you can also make one.
By account I mean the program will give you a random 8 digit number.
I also have a FileWriter which creates a file based on the ID you were given. And I have a FileReader which will eventually read what you previously exported to your file so you can update it.
The problem I have is that when I ask the user if they have an account already, if they say yes it will ask the user for their UserID.
My plan was that when it read your UserID it would scan the folder I have my .java file saved in and look for a .txt file with the same name as your UserID. For example, if you make an account and the UserID it gives you is 12345678 it will create a file named 12345678 and then when you input you UserID it will scan to see if that file exists.
Currently The problem that occurs is the it prints
Error File Not Found(the catch String I wrote)
even though I have that file in the folder.
I think there is something wrong with how I am comparing to see if the UserID matches any file name.
The "Login" class.
import java.awt.*;
import hsa.Console;
import java.util.Random;
import java.io.*;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Login
{
static Console c;
static Login player1;
public static void main (String[] args)
{
player1 = new Login ();
player1.FileReaderTest (25756326);
//player1.Userlogin (); //I think it has something to do with this
} // main method
public void Userlogin (File input)
{
c = new Console ();
Random rand = new Random ();
c.println ("Hello do you have an account?");
String Q1 = c.readLine ();
Q1 = Q1.toUpperCase ();
if (Q1.equals ("YES"))
{
c.println ("Please input your User ID");
int login = c.readInt ();
if (String.valueOf(login).equals (input))//I think it has something to do with this
{
try
{
FileReader reader = new FileReader (input);
BufferedReader buf = new BufferedReader (reader);
String line1 = buf.readLine ();
String line2 = buf.readLine ();
buf.close ();
c.println (line1);
c.println (line2);
}
catch (FileNotFoundException e)
{
c.println ("Error File Not Found");
}
catch (Exception e)
{
c.println ("ERROR");
}
}
}
else if (Q1.equals ("NO"))
{
c.println ("Please enter your name ");
String name = c.readLine ();
int UserID = rand.nextInt (99999999);
c.println ("Your User ID is " + UserID);
player1.FileCreation (UserID);
player1.FileReaderTest (UserID);
}
while (!Q1.equals ("YES") && !Q1.equals ("NO")) //While Q1 != YES || NO
{
c.println ("Please Answer the question with Yes or No");
c.println ("Hello do you have an account?");
String Q2 = c.readLine ();
Q2 = Q2.toUpperCase ();
if (Q2.equals ("YES"))
{
c.println ("Ok lets start");
break;
}
else if (Q2.equals ("NO"))
{
c.println ("Please enter your name ");
String name = c.readLine ();
int UserID = rand.nextInt (89999999) + 10000000;
c.println ("Your User ID is " + UserID);
player1.FileCreation (UserID);
player1.FileReaderTest (UserID);
break;
}
} //While Q1 != YES || NO
} //Public void Main
public void FileReaderTest (int UserID)
{
File input = new File (String.valueOf (UserID));
player1.Userlogin (input);
try
{
FileReader reader = new FileReader (input);
BufferedReader buf = new BufferedReader (reader);
String line1 = buf.readLine ();
String line2 = buf.readLine ();
buf.close ();
c.println (line1);
c.println (line2);
}
catch (FileNotFoundException e)
{
c.println ("Error File Not Found");
}
catch (Exception e)
{
c.println ("ERROR");
}
}
public void FileCreation (int UserID)
{
try
{
Writer writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (String.valueOf (UserID)), "utf-8"));
}
catch (IOException ex)
{
}
}
} // Login class
So, you have a File input, and you want to compare the name of the file, so you instead want
String.valueOf(login).equals (input.getName());
If you are getting an error on
File input = new File (String.valueOf (UserID));
then note: "2.txt", for example, is very different than a file named just "2" (which is worth mentioning because Windows hides file extensions by default)
And if you aren't giving the full path to the file, then that file has to be in your "classpath", which if you don't understand, better to give the full path to the file.
FileNotFound is not thrown after a comparison but by your FileReader when it is created. FileReader tells you that there is not file named as such. Since you said that you did create the file, there can be a few explanations:
Maybe the file you created is in the wrong folder. The default folder for a java program is the project folder. Make sure that you have your file in the right folder. Else you can give the full path as an argument for the FileReader: "/my/full/path/filename.extension".
It can also be a problem of extension. If you are using a Windows OS, the extension may be hidden in the file explorer. Right clic on your file and check whether there is such an extension (ex: ".txt")
Eventually you can open the file with a FileWriter under Java, and try to create the file within your program. You will see more easily which file Java is trying to access and it will help you identify your issue.
Since you have mentioned that you need to create the text file associated with the UserId, I would suggest adding the ".txt" in the FileReaderTest class. Something similar to this :
File input = new File (String.valueOf (UserID)+".txt");
Or more conveniently
File input = new File (Integer.toString(UserID)+".txt");
I think this solves your query.

Searching a list of names in a text file from user input

I'm currently in an Introductory Java class at University and I'm having a bit of trouble. Last semester we started with Python and I became very acquainted with it and I would say I am proficient now in writing Python; yet Java is another story. Things are alot different. Anyway, Here is my current assignment: I need to write a class to search through a text document (passed as an argument) for a name that is inputted by the user and output whether or not the name is in the list. The first line of the text document is the amount of names in the list.
The text document:
14
Christian
Vincent
Joseph
Usman
Andrew
James
Ali
Narain
Chengjun
Marvin
Frank
Jason
Reza
David
And my code:
import java.util.*;
import java.io.*;
public class DbLookup{
public static void main(String[]args) throws IOException{
File inputDataFile = new File(args[0]);
Scanner stdin = new Scanner(System.in);
Scanner inFile = new Scanner(inputDataFile);
int length = inFile.nextInt();
String names[] = new String[length];
for(int i=0;i<length;i++){
names[i] = inFile.nextLine();
}
System.out.println("Please enter a name that you would like to search for: ");
while(stdin.hasNext()){
System.out.println("Please enter a name that you would like to search for: ");
String input = stdin.next();
for(int i = 0;i<length;i++){
if(input.equalsIgnoreCase(names[i])){
System.out.println("We found "+names[i]+" in our database!");
break;
}else{
continue;
}
}
}
}
}
I am just not getting the output I am expecting and I cannot figure out why.
Try this
You should trim() your values as they have extra spaces
if(input.trim().equalsIgnoreCase(names[i].trim()))
I have run your example it runs perfectly after using trim(), you have missed to trim()
Create a seperate scanner class to read line by line.You can use BufferedReader also.
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String str= scanner.nextLine();
if(str.contains(name)) {
// Found the input word
System.out.println("I found " +name+ " in file " +file.getName());
break;
}
}
If you use Java 8:
String[] names;
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
names = stream.skip(1).toArray(size -> new String[size]);
} catch (IOException e) {
e.printStackTrace();
}

Program does not scan a text file (Java)

I was having trouble getting my program to read from a file "lexicon.txt"
My task was to have the program scan a user input and getting the word count for the program in return. Do you guys know what's going on in my code?
import java.io.*;
import java.util.Scanner;
public class searchFile {
public static void main (String args[]) throws IOException {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the file name (e.g: nonamefile.txt)");
String objective = reader.nextLine();
if (!(objective.equals("lexicon.txt"))) {
System.out.println("ERROR: Missing File");
}
else {
Scanner reader2 = new Scanner(System.in);
Scanner lexicon = new Scanner(new File("lexicon.txt"));
int wordCount = 0;
System.out.println("What word do you need to look up?");
String objective2 = reader2.nextLine();
while (lexicon.hasNext()) {
String word = lexicon.next();
if (word.equalsIgnoreCase(objective2)){
wordCount++;
}
}
System.out.println("Word count = " + wordCount);
}
} // end main method (String Args[])
} // end class searchFile
I ran your code on my computer. It is to help you. may be you are not doing same.
Please enter the file name (e.g: nonamefile.txt)
lexicon.txt
What word do you need to look up?
three
Word count = 3
The text I used in lexicon.txt was that :
one
two two
three three three
And it is working fine.
Remember, just copy paste is not like what you think it. there could be any character in clipboard when you copy that you cannot see, and pasting it also pastes these code too in your text file.
Scanner.next() looks for the next string delimited by word boundries.
Suppose there is a text that you copy pasted :
which is not visible in notepad :
So when you will search for "Hello", it will not be there.
You will have to search for instead, but you cannot write this easily.

Reading a string with new lines from console java

I want to read this string (from console not file) for example:
one two three
four five six
seven eight nine
So I want to read it per line and put every line in an array.
How can I read it? Because if I use scanner, I can only read one line or one word (nextline or next).
what I mean is to read for example : one two trhee \n four five six \n seven eight nine...
You should do by yourself!
There is a similer example:
public class ReadString {
public static void main (String[] args) {
// prompt the user to enter their name
System.out.print("Enter your name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
userName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the name, " + userName);
}
} // end of ReadString class
To answer the question as clarified in the comment on the first answer:
You must call Scanner's nextLine() method once for each line you wish to read. This can be accomplished with a loop. The problem you will inevitably encounter is "How do I know big my result array should be?" The answer is that you cannot know if you do not specify it in the input itself. You can modify your programs input specification to require the number of lines to read like so:
3
One Two Three
Four Five
Six Seven Eight
And then you can read the input with this:
Scanner s = new Scanner(System.in);
int numberOfLinesToRead = new Integer(s.nextLine());
String[] result = new String[numberOfLinesToRead];
String line = "";
for(int i = 0; i < numberOfLinesToRead; i++) { // this loop will be run 3 times, as specified in the first line of input
result[i] = s.nextLine(); // each line of the input will be placed into the array.
}
Alternatively you can use a more advanced data structure called an ArrayList. An ArrayList does not have a set length when you create it; you can simply add information to it as needed, making it perfect for reading input when you don't know how much input there is to read. For example, if we used your original example input of:
one two trhee
four five six
seven eight nine
You can read the input with the following code:
Scanner s = new Scanner(System.in);
ArrayList<String> result = new ArrayList<String>();
String line = "";
while((line = s.nextLine()) != null) {
result.add(line);
}
So, rather than creating an array of a fixed length, we can simply .add() each line to the ArrayList as we encounter it in the input. I recommend you read more about ArrayLists before attempting to use them.
tl;dr: You call next() or nextLine() for each line you want to read using a loop.
More information on loops: Java Loops
Look at this code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class SearchInputText {
public static void main(String[] args) {
SearchInputText sit = new SearchInputText();
try {
System.out.println("test");
sit.searchFromRecord("input.txt");
System.out.println("test2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void searchFromRecord(String recordName) throws IOException {
File file = new File(recordName);
Scanner scanner = new Scanner(file);
StringBuilder textFromFile = new StringBuilder();
while (scanner.hasNext()) {
textFromFile.append(scanner.next());
}
scanner.close();
// read input from console, compare the strings and print the result
String word = "";
Scanner scanner2 = new Scanner(System.in);
while (((word = scanner2.nextLine()) != null)
&& !word.equalsIgnoreCase("quit")) {
if (textFromFile.toString().contains(word)) {
System.out.println("The word is on the text file");
} else {
System.out.println("The word " + word
+ " is not on the text file");
}
}
scanner2.close();
}
}

Categories