Search modify and delete from text file - java

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.

Related

how to skip a character when read strings from a file in Java

For example, the content of a file is:
black=white
bad=good
easy=hard
So, I want to store in a map this words as key and value (ex: {black=white, bad=good} ). And my problem is when I read string I have to skip a char '=' which disappears key and value. How to make this?
In code below I make a code which read key and value from file, but this code works just when between words is SPACE, but I have to be '='.
System.out.println("File name:");
String pathToFile = in.nextLine();
File cardFile = new File(pathToFile);
try(Scanner scanner = new Scanner(cardFile)){
while(scanner.hasNext()) {
key = scanner.next();
value = scanner.next();
flashCards.put(key, value);
}
}catch (FileNotFoundException e){
System.out.println("No file found: " + pathToFile);
}
Use the split method of String in Java.
so after reading your line, split the string and take the key and value as so.
String[] keyVal = line.split("=");
System.out.println("key is ", keyVal[0]);
System.out.println("value is ", keyVal[1]);
You can change the delimiter for the scanner.
public static void main (String[] args) throws java.lang.Exception
{
String s = "black=white\nbad=good\neasy=hard";
Scanner scan = new Scanner(s);
scan.useDelimiter("\\n+|=");
while(scan.hasNext()){
String key = scan.next();
String value = scan.next();
System.out.println(key + ", " + value);
}
}
The output:
black, white
bad, good
easy, hard
Changing the delimiter can be tricky, and it could be better to just read each line,then parse it. For example, "\\n+|=" will split the tokens by either one or more endlines, or an "=". The end line is somewhat hard coded though so it could change depending on the platform the file was created on.
A simple "if" condition will solve it.
if (key == '='){ break;}

Searching for string in file and returning that specific line

I am working on student registration system. I have a text file with studentname, studentnumber and the student's grade stored in every line such as:
name1,1234,7
name2,2345,8
name3,3456,3
name4,4567,10
name5,5678,6
How can I search a name and then return the whole sentence? It does not get any matches when looking for the name.
my current code look like this:
public static void retrieveUserInfo()
{
System.out.println("Please enter username"); //Enter the username you want to look for
String inputUsername = userInput.nextLine();
final Scanner scanner = new Scanner("file.txt");
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputUsername)) {
// a match!
System.out.println("I found " +inputUsername+ " in file " ); // this should return the whole line, so the name, student number and grade
break;
}
else System.out.println("Nothing here");
}
The problem is with Scanner(String) constructor as it:
public Scanner(java.lang.String source)
Constructs a new Scanner that produces values scanned from the
specified string.
Parameters: source - A string to scan
it does not know anything about files, just about strings. So, the only line that this Scanner instance can give you (via nextLine() call) is file.txt.
Simple test would be:
Scanner scanner = new Scanner("any test string");
assertEquals("any test string", scanner.nextLine());
You should use other constructor of Scanner class such as:
Scanner(InputStream)
Scanner(File)
Scanner(Path)
You already have the variable that holds the whole line. Just print it like this:
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputUsername)) {
// a match!
System.out.println("I found " +lineFromFile+ " in file " );
break;
}
else System.out.println("Nothing here");
}

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:

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.

Categories