Getting input inside a loop using Java - 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());
}

Related

How do I check for \n when using java scanner?

I'm trying to write a scanner so that every time \n is detected, it will scan the line after that until a new \n shows up. I first tried something like this.
import java.util.Scanner;
public class test{
public static void main(String[] args) {
String input = "first line \nsecond line \nthird line";
Scanner sc = new Scanner(input);
while(sc.hasNextLine()) {
String stuff = sc.nextLine();
System.out.println(stuff);
}
sc.close();
}
}
Which works, and the output is
first line
second line
third line
However, when I try doing the same thing with Scanner(System.in) it doesn't work the same way even with same input
import java.util.Scanner;
public class test{
public static void main(String[] args) {
System.out.println("Please enter things");
Scanner cmd = new Scanner(System.in); //input: "first \n second \n third"
String input = cmd.nextLine();
Scanner sc = new Scanner(input);
while(sc.hasNextLine()) {
String stuff = sc.nextLine();
System.out.println(stuff);
}
cmd.close();
sc.close();
}
}
Output:
first \n second \n third
What should I change, so that every \n will print a new line?
EDIT:
If the input was
first
second
third
and entered into the prompt at once, would scanner.nextLine() be enough to suffice?
System.out.println("Please enter things");
Scanner cmd = new Scanner(System.in); //input: "first \n second \n third"
while(cmd.hasNext()) {
String word = cmd.next();
if(word.equals("\\n")) {
System.out.println();
}else {
System.out.print(word);
}
}
In all honesty, you will need to utilize these sub-strings at some point outside of your while loop so it would actually be better to split the line based on the same delimiter and have each substring as a element within a String Array This way you don't need to utilize Scanner and a while loop for this at all, for example:
String input = "first line \n second line \n third line"; // Read in data file line...
String[] stuffArray = input.split("\\s+?\n\\s+?");
System.out.println(Arrays.toString(stuffArray));
System.out.println();
System.out.println(" OR in other words");
System.out.println();
for(String str : stuffArray) {
System.out.println(str);
}
If you want to do this using System.in:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text:");
String stuff = sc.nextLine();
String[] subArray = stuff.trim().split("(\\s+)?(\\\\n)(\\s+)?");
System.out.println();
// Display substrings...
for (String strg : subArray) {
System.out.println(strg);
}

My program compiles but still shows an error, java.util.NoSuchElementException

public static void cCommand(Scanner in) throws FileNotFoundException {
System.out.println();
System.out.print("Type an output file name: ");
String outFile = in.nextLine();
PrintStream ps = new PrintStream(new File("out.txt"));
Scanner input = new Scanner(new File("story.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner console = new Scanner(line);
while (input.hasNext()) {
String word = console.next();
if (word.startsWith("<") && word.endsWith(">")) {
char first = word.charAt(1);
String a = aeiou(first);
word = word.replace("<"," ");
word = word.replace(">"," ");
word = word.replace("-"," ");
System.out.print("Please type" + a + word + ": ");
String replace = in.next();
ps.print(" " + replace);
} else {
ps.print(" " + word);
}
}
}
} //end of cCommand method
this error pops up:
Type an output file name: Exception in thread "main" java.util.NoSuchElementException
NoSuchElementException error is because either
String replace = in.next();
or
String word = console.next();
still calling next but one of them no longer has a next element to provide. Make sure to call hasNext() first before calling next().

How to store input line by line from an input file into variables

I am trying to store input of certain data types into variables and print them out into a output file but my code does not seem to work. If I enter the input through std in with System.in Scanner and print to stdout, my code will work. However, when I try what I have, I keep getting this:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Queue.main(Queue.java:17)
Here is my code:
import java.util.*;
import java.io.*;
public class Queue {
public static void main(String[] args) throws IOException {
// open files
// takes input from test-input.txt
Scanner input = new Scanner(new File("test-input.txt"));
// prints output to test-output.txt
PrintWriter output = new PrintWriter(new FileWriter("test-output.txt"));
//Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
int teller = input.nextInt();
String name = input.next();
int simTime = input.nextInt();
int transTime = input.nextInt();
output.println(teller + " " + name + " " + simTime + " " + transTime);
}
// close files
input.close();
output.close();
}
}
My input file contains lines such as:
1 Jesse 2 9
2 Wilson 1 4
3 King 4 8
4 Andy 6 7
You're never consuming the newline character after the transTime
int transTime = input.nextInt();
input.nextLine();
You could also consume the entire line at once, and then split it into types
Try to make sure you are parsing a non empty line, it can happen if your file has extra empty lines, so i suggest do a check inside your while statement
while (input.hasNextLine()) {
final String line = input.nextLine().trim();
if (line.isEmpty()) continue; // continue if line is empty
String [] items = line.split("\\s+");
int teller = Integer.parseInt(items[0]);
String name = items[1];
int simTime = Integer.parseInt(items[3]);
int transTime = Integer.parseInt(items[3]);
output.println(teller + " " + name + " " + simTime + " " + transTime);
}

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

Updating an old line inside a text file

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.

Categories