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

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().

Related

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

Reading multiple lines into a scanner object in Java

I'm having a bit of trouble figuring out how to read multiple lines of user input into a scanner and then storing it into a single string.
What I have so far is down below:
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text:");
String input = "";
String nextLine = keyboard.nextLine();
while(keyboard.hasNextLine()){
input += keyboard.nextLine
};
return input;
}
then the first three statements of the main method is:
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString );
My goal is to have it where once the user types their text, all they have to do is hit Enter twice for everything they've typed to be displayed back at them (following "Current text: "). Also I need to store the string in the variable userString in the main (I have to use this variable in other methods). Any help at all with this would be very much appreciated. It's for class, and we can't use arrays or Stringbuilder or anything much more complicated than a while loop and basic string methods.
Thanks!
Using BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
String line;
while((line = br.readLine()) != null){
if(line.isEmpty()){
break; // if an input is empty, break
}
input += line + "\n";
}
br.close();
System.out.println(input);
Or using Scanner:
String input = "";
Scanner keyboard = new Scanner(System.in);
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
System.out.println(input);
For both cases, Sample I/O:
Welcome to Stackoverflow
Hello My friend
Its over now
Welcome to Stackoverflow
Hello My friend
Its over now
Complete code
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString);
}
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text: ");
String input = "";
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
return input;
}

Asking for a word and checking its number of occurrence in a text file

public class Try{
public static void main (String args[]) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Try.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String Word=sc.next();
String line=in.readLine();
int count =0;
String s[];
do
{
s=line.split(" ");
for(int i=0; i < s.length; i++)
{
String a = s[i];
if(a.contains(Word))
count++;
}
line=in.readLine();
}while(line!=null);
System.out.print("There are " +count+ " occurences of " +Word+ " in ");
java.io.File file = new java.io.File("Try.txt");
Scanner input = new Scanner(file);
while(input.hasNext())
{
String word = input.nextLine();
System.out.print(word);
}
}
}
The intended purpose of my program is to ask the user for a certain word(s) that will be checked in a text file and if it exists, it will count the number of times the user-entered word occurs in the text file. So far, my program can only search for one word. If I try two words separated by space, only the first word will be searched and counted for its number of occurrence. Any tips on how to search multiple words?
I was following literally the title of the question and therefore I will suggest this algorithm:
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Test.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String word = sc.next();
String line = in.readLine();
int count = 0;
// here is where the efficiently magic happens
do {
// 1. you dont need to split a line by spaces, too much overhead...
// 2. and you dont need to do counter++
// 3. do instead: calculate the number of coincidences that the word is
//repeated in a whole line...that is what the line below does..
count += (line.length() - line.replace(word, "").length()) / word.length();
//the rest looks fine
//NOTE: if you need a whole word then wrap the input of the user and add the empty spaces at begin and at the end...so the match will be perfect to a word
line = in.readLine();
} while (line != null);
System.out.print("There are " + count + " occurences of " + word + " in ");
}
Edit:
if you want to check more than one word in the document then use this
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Test.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String input = sc.nextLine();
String[] word = input.split(" ");
String line = in.readLine();
int count = 0;
do {
for (String string : word) {
count += (line.length() - line.replace(string, "").length()) / string.length();
}
line = in.readLine();
} while (line != null);
System.out.print("There are " + count + " occurences of " + Arrays.toString(word) + " in ");
}

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

Exception in main thread java.util.NoSuchElementException

I'm working on this project to improve my skill in Java. My goal is to write a program that reads the line from a specified doc or text file (depending on which the user wants to open; int 2 or 1 respectively.) and then asks the user to input their document name (without the file extension), and then reads the first line in the document or text file. I want it to do this as many times as the user wants. But I keep getting NoSuchElementException while executing the code.
public class switches {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("How many files would you like to scan?");
System.out.println("Enter # of files to scan: ");
int countInput = input.nextInt();
input.close();
for (int count = 0; count < countInput;) {
System.out.println("Please enter a file name to scan. ");
System.out.println("1 for .txt, 2 for .doc");
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
switch (choice) {
default: {
do {
System.out.println("Please pick "
+ "either 1: txt or 2: doc");
choice = keyboard.nextInt();
} while (choice != 1 && choice != 2);
}
case 1: {
System.out.println("Txt file name:");
keyboard.nextLine();
String txtName = keyboard.nextLine();
File openTxtFile = new File("C:/Users/Hp/Documents/" + txtName
+ ".txt");
Scanner firstTxtLine = new Scanner(openTxtFile);
String printedTxtLine = firstTxtLine.nextLine();
firstTxtLine.close();
System.out.println("The first line " + "of your text file is: "
+ printedTxtLine);
keyboard.close();
count++;
break;
}
case 2: {
System.out.println("Doc file name:");
keyboard.nextLine();
String docName = keyboard.nextLine();
File openDocFile = new File("C:/Users/Hp/Documents/" + docName
+ ".doc");
Scanner firstLine = new Scanner(openDocFile);
String printedDocLine = firstLine.nextLine();
firstLine.close();
System.out.println("The first line"
+ " of your word document is: " + printedDocLine);
keyboard.close();
count++;
break;
}
}
}
}
}
If you remove the line input.close(); on line 14. This should solve your problem. According to the documentation, it will throw a NoSuchElementException - "if input is exhausted".

Categories