Updating an old line inside a text file - java

Okay, so i have an issue trying to update a line or sentence in a text file.
The way my program works is this: If a user enters a question the program searches the text file for that exact question(lets say is n). The answer to the question would be on the following line(n + 1). My issue is trying to update the following line(n + 1) to some new line entered by the user.
I keep getting a Exception in thread "main" java.util.NoSuchElementException: No line found when i try to update the line in the text file. my removedata() is where i am trying to update the line of text.
Here is my code
public static void removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
public static void parseFile(String s) throws IOException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
Scanner forget = new Scanner(System.in);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
System.out.println(scanner.nextLine());
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); // NoSuchElementException
// error
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
}
}
}
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();
}
My text file is :
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 ten dollars
Can someone help me solve this issue?

Change the code in the if block in parsefile to
String temp = scanner.nextLine();
System.out.println(temp);
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(temp); // NoSuchElementException
// error
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
for an explanation why this works, look at Nick L.s answer.

The problem is here:
while (scanner.hasNextLine()) { //(1)
final String lineFromFile = scanner.nextLine(); //(2)
if (lineFromFile.contains(s)) { //(3)
System.out.println(scanner.nextLine()); //(4)
//....
String yellow = forget.nextLine(); //(5)
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); //(6)
}
}
//....
}
First of all, you are correctly iterating the scanner lines checking whether there is a line (1). Now, you are getting the first line of the scanner on (2), but if the condition (3) succeeds, you are retrieving the next line again at (4) inside System.out.println(....). Same thing applies to (5) and (6) accordingly.
Now, imagine that you have reached the end of file at (2) and the condition at (3) succeeds. You will receive an exception of no such line, as you logically have. The same can happen at (5) and (6).
Each call of the nextLine(), will get the next line of the file opened on the stream.
I suggest that you do one readline inside the loop, then apply the received string when needed.

Related

Command line arguments

I've been doing some exercises from my study book, and I can't seem to figure out this specific one. The instructions are: repeat Exercise P7.2, but allow the user to specify the file name on the command line. If the user does not specify any file name, then prompt the user for the name.
Ín P7.2, which I've completed, we were supposed to write a program that reads a file containing text, read each line and send it to the output file, preceded by line numbers. Basically, what I'm wondering is what I'm supposed to do exactly?
This is my code right now:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter name of file for reading: ");
String fileNameReading = input.next();
System.out.print("Enter name of file for writing: ");
String fileNameWriting = input.next(); om
input.close();
File fileReading = new File(fileNameReading);
Scanner in = null;
File fileWriting = new File(fileNameWriting);
PrintWriter out = null;
try {
in = new Scanner(fileReading);
out = new PrintWriter(fileWriting); fileWriting
} catch (FileNotFoundException e1) {
System.out.println("Files are not found!");
}
int lineNumber = 1;
while (in.hasNextLine()) {
String line = in.nextLine();
out.write(String.format("/* %d */ %s%n", lineNumber, line));
lineNumber++;
}
out.close();
in.close();
System.out.println();
System.out.println("Filen was read and re-written!");
}
I think your exercise just requires a small refactor to use the command line arguments to specify the file for reading:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String fileNameReading;
// check if input file were passed as a parameter
if (args != null && args.length > 0) {
fileNameReading = args[0];
}
// if not, then prompt the user for the input filename
else {
System.out.print("Enter name of file for reading: ");
fileNameReading = input.next();
}
System.out.print("Enter name of file for writing: ");
String fileNameWriting = input.next();
// rest of your code as is
}
You would run your code, for example, as:
java YourClass input.txt
Here we pass in the name of the input file as a parameter.

Writing a program in Java to read in multiple strings from user and compare to text file

I am attempting to write a program that will take user input ( a long message of characters), store the message and search a text file to see if those words occur in the text file. The problem I am having is that I am only ever able to read in the first string of the message and compare it to the text file. For instance if I type in "learning"; a word in the text file, I will get a result showing that is is found in the file. However if I type "learning is" It will still only return learning as a word found in the file even though "is" is also a word in the text file. My program seems to not be able to read past the blank space. So I suppose my questions is, how do I augment my program to do this and read every word in the file? Would it also be possible for my program to read every word, with or without spaces, in the original message taken from the user, and compare that to the text file?
Thank you
import java.io.*;
import java.util.Scanner;
public class Affine_English2
{
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
for(int i = 0; i < message.length(); i++)
{
if(line.indexOf(message) != -1)
{
System.out.println(message + " is an English word ");
break;
}
}
}
}
}
I recommend you first process the file and build a set of legal English words:
public static void main(String[] args) throws IOException {
Set<String> legalEnglishWords = new HashSet<String>();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine()) {
String line = file.nextLine();
for (String word : line.split(" ")) {
legalEnglishWords.add(word);
}
}
file.close();
Next, get input from the user:
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
String message = input.nextLine();
input.close();
Finally, split the user's input to tokens and check each one if it is a legal word:
for (String userToken : message.split(" ")) {
if (legalEnglishWords.contains(userToken)) {
System.out.println(userToken + " is an English word ");
}
}
}
}
You may try with this. With this solution you can find each word entered by the user in your example.txt file:
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.nextLine();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine())
{
String line = file.nextLine();
for (String word : message.split(" "))
{
if (line.contains(word))
{
System.out.println(word + " is an English word ");
}
}
}
}
As Mark pointed out in the comment, change
scan.next();
To:
scan.nextLine();
should work, i tried and works for me.
If you can use Java 8 and Streams API
public static void main(String[] args) throws Exception{ // You need to handle this exception
String message = "";
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = input.nextLine();
List<String> messageParts = Arrays.stream(message.split(" ")).collect(Collectors.toList());
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
reader.lines()
.filter( line -> !messageParts.contains(line))
.forEach(System.out::println);
}
You have many solution, but when it comes to find matches I suggest you to take a look to the Pattern and Matcher and use Regular Expression
I haven't fully understood your question, but you could do add something like this (I did not tested the code but the idea should work fine):
public static void main(String[] args) throws IOException{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
String pattern = "";
for(String word : input.split(" ")){
pattern += "(\\b" + word + "\\b)";
}
Pattern r = Pattern.compile(pattern);
while(file.hasNextLine())
{
String line = file.nextLine();
Matcher m = r.matcher(line);
if(m.matches()) {
System.out.println("Word found in: " + line);
}
}
}

Getting input inside a loop using Java

I'm trying to use scanner.nextLine() inside a loop, but I get an exception.
The problem is located in this part of the code.
while(!sentence.equals("quit")){
dealWithSentence(sentence, voc);
System.out.println("Enter your sentence:");
sentence = scanner.nextLine();
}
There is the exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at il.ac.tau.cs.sw1.ex4.SpellingCorrector.main(SpellingCorrector.java:34)
That's my full method code:
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
String filePath = scanner.nextLine();
if (filePath.contains(" ")){
scanner.close();
throw new Exception("[ERROR] the file path isnt correct");
}
File file = new File(filePath);
String[] voc = scanVocabulary(new Scanner(file));
if (voc == null)
{
scanner.close();
throw new Exception("[ERROR] the file isnt working");
}
System.out.println("Read " + voc.length + " words from " + file.getName());
System.out.println("Enter your sentence:");
String sentence = scanner.nextLine();
while(!sentence.equals("quit")){
dealWithSentence(sentence, voc);
System.out.println("Enter your sentence:");
sentence = scanner.nextLine();
}
scanner.close();
Scanner.nextLine() works as follows..
String s = "Hello World! \n 3 + 3.0 = 6.0 true ";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// print the next line
System.out.println("" + scanner.nextLine());
// print the next line again
System.out.println("" + scanner.nextLine());
// close the scanner
scanner.close();
}
this will give you the following output
Hello World!
3 + 3.0 = 6.0 true
So basically it starts scanning and skips until the first new line character, and then it returns whatever it has skipped so far as the output. In your case if you have only a single sentence and no new line (\n) in it at all, it will skip the entire length and never find a new line. thereby throwing the exception... add a new line character in mid of sentence and see if the exception goes away
Credits go to : http://www.tutorialspoint.com/java/util/scanner_nextline.htm
Check scanner.hasNextLine() before you use scanner.nextLine():
if (scanner.hasNextLine()) {
sentence = scanner.nextLine();
}
Otherwise, the scanner might not have any element and cannot provide a next line.
Usually, you will read your input in a loop, such as:
while (scanner.hasNextLine()) {
System.out.println("Line: " + scanner.nextLine());
}

Searching a file for Keyword,then outputting the entire sentence containing keyword

I am quite new to Java programming and I have encounter a problem. My problem is instead of returning a sentence from the text file, only the keyword is returned. Eg i entered " who had a good day today?" only "day" is returned. Let's say a text file contains "Paula had a good day today" My goal was to return "Paula had a good day today" and here is my code.
The issues are with the parseFile method and my if statement where i call the parseFile ()
public static void parseFile(String s) throws FileNotFoundException {
File file = new File("today.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(s);
break;
}
}
}
this is my main
public static void main(String args[]) throws ParseException,
FileNotFoundException {
String[] keywords = { "day", "What book", "not going ", "okay"};
boolean endloop = false;
boolean found = false;
Scanner scanner = new Scanner(System.in);
String input = null;
System.out.println("What's up?");
do {
System.out.print(" - ");
input = scanner.nextLine().toLowerCase();
for (String keyword: keywords) {
if (input.contains(keyword)) {
//System.out.println("Found keyword!"+ keyword);
// TODO: You can optimize this
parseFile(keyword);
}
}
if (!found) {
System.out
.println("I am sorry I do not know");
}
break;
}
while (!input.equalsIgnoreCase("thanks"));
System.out.println(" Have a good day!");
}
}
"today.txt" Contains
Paula is having a good day.
Carla asked What is a good book to read.
Any help would be greatly appreciated
where you do
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(s);
break;
}
you print out "s" which is the thing you're looking for,
but you want to print out the line. which is "lineFromFile"
so you might want to do
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
break;
}
You are printing s which is that word used for searching. you should be printing the variable lineFromfile as it contains the value from file
public static void parseFile(String s) throws FileNotFoundException {
File file = new File("today.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
break;
}
}
}

I have to make a loop taking a users input until "done" is entered

I'm trying to make an ArrayList that takes in multiple names that the user enters, until the word done is inserted but I'm not really sure how. How to achieve that?
ArrayList<String> list = new ArrayList<String>();
String input = null;
while (!"done".equals(input)) {
// prompt the user to enter an input
System.out.print("Enter input: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the input from the command-line; need to use try/catch with the
// readLine() method
try {
input = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read input!");
System.exit(1);
}
if (!"done".equals(input) && !"".equals(input))
list.add(input);
}
System.out.println("list = " + list);
I would probably do it like this -
public static void main(String[] args) {
System.out.println("Please enter names seperated by newline, or done to stop");
Scanner scanner = new Scanner(System.in); // Use a Scanner.
List<String> al = new ArrayList<String>(); // The list of names (String(s)).
String word; // The current line.
while (scanner.hasNextLine()) { // make sure there is a line.
word = scanner.nextLine(); // get the line.
if (word != null) { // make sure it isn't null.
word = word.trim(); // trim it.
if (word.equalsIgnoreCase("done")) { // check for done.
break; // End on "done".
}
al.add(word); // Add the line to the list.
} else {
break; // End on null.
}
}
System.out.println("The list contains - "); // Print the list.
for (String str : al) { // line
System.out.println(str); // by line.
}
}
String[] inputArray = new String[0];
do{
String input=getinput();//replace with custom input code
newInputArray=new String[inputArray.length+1];
for(int i=0; i<inputArray.length; i++){
newInputArray[i]=inputArray[i];
}
newInputArray[inputArray.length]=input
intputArray=newInputArray;
}while(!input.equals("done"));
untested code, take it with a grain of salt.
ArrayList<String> names = new ArrayList<String>();
String userInput;
Scanner scanner = new Scanner(System.in);
while (true) {
userInput = scanner.next();
if (userInput.equals("done")) {
break;
} else {
names.add(userInput);
}
}
scanner.close();

Categories