Searching for a string in a text file using Java - 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();

Related

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();
}

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 particular line of text in a text file

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:

while loop error in Java

well im currently learning java my myself but from what i know i just cant seem to fix this problem
currently testing a script where if u dont type ur name exactly u must re-type it but this error appears i searched everywhere but most of the things i tried dont work
Please type in your name:
lucas
Welcome lucas
Confirm your name:
luca
Please type in your name:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at input.main(input.java:9)
here is the code:
import java.util.Scanner;
public class input {
public static void main(String[] args) {
while (true) {
try (Scanner input = new Scanner(System.in)) {
System.out.println("Please type in your name: ");
String name = input.nextLine();
System.out.println("Welcome " + name);
if (name.equals("nico")) {
System.out.println("bitch");
break;
} else {
System.out.println("Confirm your name:");
String name1 = input.nextLine();
if (name1.equals("nico")) {
System.out.println("Hello " + name1 + "... bitch");
} else if (name1.equals(name)) {
System.out.println("Thank you");
break;
}
}
}
}
}
}
Move the try-with-resources to around your while loop. When execution leaves the try-with-resources, Java closes the resources. Here, that resource is the standard input, which cannot be re-opened.
try (Scanner input = new Scanner(System.in)) {
while (true) {
System.out.println("Please type in your name: ");
You actually don't really need the try-with-resources here. Don't close standard input/output/error.
Don't put the Scanner into your loop.
Loop while the scanner still has input.
Currently, you create new Scanner too often.

Java: How to get my code to loop a check for if a file exists AND if a file doesn't exist with two different actions?

I'm having an issue with my code, where the loop works fine if a file exists, but if it doesn't then it only repeats once. I'd like it to work so that if a user enters a filename, and that file exists, it outputs that files content, and then asks the name of a new file. It should keep doing this until the user enters an escape word. If the file doesn't exist, it should tell them the file doesn't exist, and then prompt them to enter a new file name to see if it exists. This should loop continuously until the escape word is entered. Once the escape word is entered, it should output the end game message.
I need to accomplish this without using methods, since it's for a college beginning java class. I have only a few weeks of coding experience and I'm completely stuck on getting this to function properly. My teacher suggested to "use an if else block to make the 2 paths mutually exclusive," although I'm not quite sure what this means or how to accomplish it.
Can anyone help me fix my code to accomplish the above?
Relevant code:
while (!filename.equals(escapeWord))
{
System.out.print("\nWhere would you like to go?\n");
filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
if (!file.exists())
{
System.out.println("You can't go that way!");
return;
}
while (inputFile.hasNext())
{
String fileRead = inputFile.nextLine();
System.out.println(fileRead);
dayCount += 1;
}
inputFile.close();
}
//End Game Message
System.out.println("Congratulations, your adventure is over. " +
"You spent " +dayCount + " days adventuring!");
First of all I would move the check for the escape word into the loop.
Secondly the check for the file would have thrown you out of your loop.
while (true)
{
System.out.print("\nWhere would you like to go?\n");
filename = keyboard.nextLine();
if(filename.equals(escapeWord))
{
break;
}
File file = new File(filename);
if (!file.exists())
{
System.out.println("You can't go that way!");
continue;
}
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
String fileRead = inputFile.nextLine();
System.out.println(fileRead);
dayCount += 1;
}
inputFile.close();
}
Not much sure but I think the return statement causing the issue; returning back to the caller if file don't exist. Remove that return and just say continue; so if file don't exist then it will go for the next iteration.
if (!file.exists())
{
System.out.println("You can't go that way!");
return; <-- Here
}
Should look like
if (!file.exists())
{
System.out.println("You can't go that way!");
continue;
}

Categories