I am trying to read a paragraph in java via Scanner class and printout the line. However, I encoutner a very strange issue. I get the following error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Unknown Source)
at Test.main(Test.java:10)
and the print before that is not the end of the file. The print stops at the first word on a specific line every time and there are 5-6 lines more in the file.
My code:
try {
Scanner scanner = new Scanner(new File(filename));
for (int i = 1; i < 3801; i++){
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Use the following to determine the end of file instead of hardcoded integer.
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
Your scanner.nextLine() is in a for-loop.
It is recommended that you use a while-loop instead.
The condition of the while-loop should be scanner.hasNextLine() which basically translates to "While the scanner has another line ahead in the file, run the code inside the while-loop, otherwise stop the while-loop"
That way, if the scanner doesn't have any more lines to read, it simply stops the loop and continues with the rest of the code.
In your for-loop, you are forcing the scanner to keep reading the file even though it has no other lines to read.
The code should be:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("read.txt"));
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
Apparently java was confused by the encoding of the file and that is why it was crashing. After adding "UTF-8" in the scanner class now it read everything fine.
Related
I am a beginner with java and programmin over all, So this the full code for a file reader program that counts words or displays text file content, I wanted to take user inputs for commands that I indicated using an if statement, but String printFileCommand = scan.nextLine(); is not working due to the error addressed below:
package com;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReader {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanTwo = new Scanner(System.in);
System.out.println("Please Enter Your File Path");
String filePath = scanTwo.nextLine();
scanTwo.close();
File fileInput = new File(filePath);
Scanner fileScanner = new Scanner(fileInput);
System.out.println(fileScanner.nextLine());
fileScanner.close();
System.out.println("Commands: PRINT.FILE --> Prints all file COUNT.WORDS --> Counts all words");
System.out.println("Type Command:");
Scanner scan = new Scanner(System.in);
String printFileCommand = scan.nextLine(); <----ERROR HERE
scan.close();
if (printFileCommand.contains("PRINT.FILE")) {
while (fileScanner.hasNextLine()) {
System.out.println(fileScanner.nextLine());
}
} else if (printFileCommand.contains("COUNT.WORDS")) {
int wordCount = 0;
while (fileScanner.hasNext()) {
String fileWords = fileScanner.next();
wordCount++;
// System.out.println(wordCount);
}
System.out.println(wordCount);
}
else {
System.out.println("COMMAND INVALID!");
}
}
}
```
**Terminal Output:**
PS C:\Users\DR\Desktop\FIRST REAL PROGRAMMING> c:; cd 'c:\Users\DR\Desktop\FIRST REAL PROGRAMMING'; & 'c:\Users\DR\.vscode\extensions\vscjava.vscode-java-debug-0.30.0\scripts\launcher.bat' 'C:\Program Files\AdoptOpenJDK\jdk-15.0.1.9-hotspot\bin\java.exe' '--enable-preview' '-XX:+ShowCodeDetailsInExceptionMessages' '-Dfile.encoding=UTF-8' '-cp' 'C:\Users\DR\AppData\Roaming\Code\User\workspaceStorage\458dc35931a3067a355426e5ceeeee32\redhat.java\jdt_ws\FIRST REAL PROGRAMMING_e263b9bc\bin' 'com.FileReader'
Please Enter Your File Path
E://texttwo.txt
This is my text file.
Commands: PRINT.FILE --> Prints all file COUNT.WORDS --> Counts all words
Type Command:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at com.FileReader.main(FileReader.java:21)
PS C:\Users\DR\Desktop\FIRST REAL PROGRAMMING>
So why is `String printFileCommand = scan.nextLine();` not working? I tried alot, but its not working...
It doesn't work because your stream for System.in is closed.
You can check it for example System.out.println(System.in.available()); and you will see:
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:159)
at java.io.BufferedInputStream.available(BufferedInputStream.java:410)
you closed it in line: scanTwo.close();
I'm still trying to understand Java myself, but I think you don't exactly need to create and use multiple Scanners to collect data. Since you are searching for strings for the file creations, you could technically do something like:
Scanner scanner = new Scanner(System.in);
String filePath = scanner.nextLine();
With some of the other scanners you can keep since you're specifically calling the fileInputs within the Scanner, but when asking the user for data, I suggest using only one scanner source, but having something like the last line of code I shared as a template for updating your code! If I misunderstood something you're more than welcome to let me know. Thanks!
Please check this question:
NoSuchElementException - class Scanner
Your code will work if you remove the code:
scanTwo.close();
Or removing better:
Scanner scan = new Scanner(System.in);
And use scanTwo for reading (but you don't have to close the scanner with scanTwo.close()).
But I recommend you to read those answers to understand how it works.
I am creating a CSV parser library in Java. I have the following code so far:
However I keep getting the error when I try to include user input to the ("Enter a delimiter") part:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at demo.CSV.main(CSV.java:19)
Also can you please help me figure out how I would create a test application that can use the library.
Thank you.
package demo;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CSV {
public static void main(String[] args) throws FileNotFoundException {
Scanner x = new Scanner(System.in);
System.out.println("Enter the File");
String s = x.next();
x.close();
Scanner scanner = new Scanner(new File(s));
scanner.useDelimiter(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
System.out.println("Enter delimiter");
Scanner scanner1 = new Scanner(System.in);
String format = scanner1.nextLine();
while(scanner.hasNext()){
System.out.println(scanner.next()+format);
}
scanner.close();
}
}
The problem boils down to the fact that you're not using Scanner.nextLine() properly, compounded by the fact that your input file is empty.
When you use nextLine(), you need to enclose it within a loop that checks to see if an input source has a next line using hasNextLine() before trying to read the line with nextLine().
Your code assumes that there's a next line without first checking. Meanwhile, your input file is empty, so you get NoSuchElementException.
Instead of going in blind like this:
String format = scanner1.nextLine();
Replace that line with this:
String format = null;
while(scanner1.hasNext())
{
format = scanner1.nextLine();
}
Then make sure you generate an input file that actually has one or more lines in it.
I am a beginner. Reading from text file in Java using a scanner. This code just to read the first 3 tokens isn't working:
try{
Scanner scFile = new Scanner (new File ("readhere.txt")).useDelimiter("#");
String first = scFile.next();
String second = scFile.next();
int third = scFile.nextInt(); // error here. Why cant I store the integer?
}
catch(FileNotFoundException e){
System.out.println("Error");
}
I am trying to read just the first 3 tokens:
Andrew#Smith#21
John#Morris#55
the problem occurs when reading 21. java.util.InputMismatchException
The scanner is including the carriage return character(s) as part of the next readable token which produces an invalid integer. You could do
Scanner scanner = new Scanner(new File("readhere.txt")).useDelimiter("#|\r\n");
I am extracting data from a file. I am having trouble with using the delimiters while reading through the file.
My file is ordered like so:
0 Name 0
1 Name1 1
The structure is an integer, a tab (\t), a string, a tab (\t), another integer, and then a newline (\n).
I have tried to use a compound delimiter as referenced in this question:
Java - Using multiple delimiters in a scanner
However, I am still getting an InputMismatch Exception when I run the following code:
while(readStations.hasNextLine()) {
327 tempSID = readStations.nextInt();
328 tempName = readStations.next();
329 tempLine = readStations.nextInt();
//More code here
}
It calls this error on line two of the above code...
I am not sure why, and help would be appreciated, Thanks.
The current output runs as such for the code:
Exception in thread "main" java.util.InputMismatchException
...stuff...
at Metro.declarations(Metro.java:329)
Newline is most likely causing you issues. Try this
public class TestScanner {
public static void main(String[] args) throws IOException {
try {
Scanner scanner = new Scanner(new File("data.txt"));
scanner.useDelimiter(System.getProperty("line.separator"));
while (scanner.hasNext()) {
String[] tokens = scanner.next().split("\t");
for(String token : tokens) {
System.out.print("[" + token + "]");
}
System.out.print("\n");
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
i think when the scanner separates input like this you can only use input.next() not next int: or keep the same type.
I have a set of instructions in a text file:
LoadA 0
LoadB 1
Add
Store 0
LoadA 2
etc...
I know I can use Scanner and hasNextLine but not sure how to implement this and have the instructions read and understood.
As much as the people above would like you to do this on your own I will answer this question because I remember how difficult it was to learn. As long as you learn from the and don't just copy them this should be useful.
Scanner sc = new Scanner(System.in); //read from the System.in
while (sc.hasNextLine()) { //this will continue to itterate until it runs out
String[] x = sc.nextLine().split(" ");
//this takes your input and puts it into a string array where there is a
//space e.g. ["LoadA", "0"]
}
I hope this helps. You are still required to solve the problem. You now have the ability to get the content now. Good luck.
Scanner inFile = null;
try
{
// Create a scanner to read the file, file name is parameter
inFile = new Scanner (new File("whatever.txt"));
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!");
// Stop program if no file found
System.exit (0);
}
then,
while(inFile.hasNextLine()){
(some variable) = inFile.nextLine();
(do something to that variable);
}
if this doesn't solve the question, I would recommend taking a look at http://www.cs.swarthmore.edu/~newhall/unixhelp/Java_files.html