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.
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.
The documentation for nextLine() says that it can throw a nosuchelementexception. But when using the nextLine() to get input for the Scanner as demonstrated in the following code, the nosuchelementexception is not thrown, The only thing that happens is by pressing "Enter" two times the programs just ends. I submitted the same code for an evaluation to an online system, there also the system said that the code throws a nosuchelementexception
What sort of an input would produce a nosuchelementexception?
String input = "";
Scanner sc = new Scanner(System.in);
input += sc.nextLine() + " ";
input += sc.nextLine() + " ";
System.out.println(input);
Here’s an example where the standard input (i.e. System.in) is piped from another application:
echo 'one line only' | java Read
Or read from a file:
java Read <file_with_one_line.txt
Or using interactive user input:
java Read
I am entering one line
Ctrl+D
These examples assume that you’ve compiled the code you’ve posted (wrapped into a class Read) to Read.class in the same directory.
import java.util.Scanner;
class Read {
public static void main(String[] args) {
String input = "";
Scanner sc = new Scanner(System.in);
input += sc.nextLine() + " ";
input += sc.nextLine() + " ";
System.out.println(input);
}
}
javac read.java
I think this is possible when reading files:
I created a new txt-file without any content (test.txt) in it and ran the following code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("test.txt");
Scanner sc = new Scanner(file);
String str = sc.nextLine();
}
}
The result:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Test.main(Test.java:9)
Edit
It can also appear with System.in because when closing one scanner it appears to also close System.in.
Consider the following code:
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
sc.nextLine();
sc.close();
sc2.nextLine();
}
}
This throws the following exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Test.main(Test.java:10)
This happens because sc (with access to System.in) was closed. This causes that System.in is not accessible anymore and therefore sc2 doesn't work properly and throws an exception.
I need help to read data from text file and give output based on user input.
Here is data I have saved in notepad under "data.txt" file
C|C,370,0.154
C||C,680,0.13
C|||C,890,0.12
C|H,435,0.11
C|N,305,0.15
C|O,360,0.14
C|F,450,0.14
C|Cl,340,0.18
O|H,500,0.10
O|O,220,0.15
O|Si,375,0.16
N|H,430,0.10
N|O,250,0.12
F|F,160,0.14
H|H,435,0.074
this is how I have data in notepad. yes, each entry is separated by comma
I know basic reading operation Scanner class reads line and spits out text from each line but this time I am inputting either number of bonds or bond length and it gives me the output of remaining two value.
Assignment:
No, I am not here to ask you to do homework but rather help me learn the process.
import java.io.*;
import java.io.FileNotFoundException;
import java.util.*;
public class LearnReadText
{
public static void main (String args[]) throws FileNotFoundException
{
Scanner input = new Scanner(System.in);
String strResponse="";
do
{
System.out.println("\nChapter 7");
System.out.println("L - Bond Length");
System.out.println("N - Bond Numbers (1=single, 2=double, 3=triple)\n");
System.out.println("Q - quit program.");
strResponse = input.nextLine();
strResponse = strResponse.toUpperCase();
Scanner file = new Scanner(new File("data.txt"));
file.close();
}
while (!strResponse.equals("Q"));
System.out.println("\n\nThank you and have a nice day.");
input.close();
}
}
on one of my Java homework assignments, I am asked to request 2 file names from a user, copy all the text from the first file, and then convert it all to uppercase letters and write it to the second file.
I have my reading and writing methods copied almost exactly as it is in my book, but I can not compile because I am getting the error that the file is not found. I have even tried removing the part where the user assigns the file names and just added the directory and file location myself but I am still getting the FileNotFound Exception.
The errors appear on lines 17 and 32.
Is there something I am doing wrong or is there a problem with Netbeans?
import java.io.*;
import java.util.Scanner;
public class StockdaleUpperfile {
public static void main(String[] args) {
String readFile, writeFile, trash;
String line, fileContents, contentsConverted;
System.out.println("Enter 2 file names.");
Scanner keyboard = new Scanner(System.in);
readFile = keyboard.nextLine();
writeFile = keyboard.nextLine();
File myFile = new File(readFile);
Scanner inputFile = new Scanner(myFile); //unreported exception FileNotFoundException; must be caught or declared to be thrown;
line = inputFile.nextLine();
fileContents=line;
while(inputFile.hasNext())
{
line = inputFile.nextLine();
fileContents+=line;
}
inputFile.close();
contentsConverted = fileContents.toUpperCase();
PrintWriter outputfile = new PrintWriter(writeFile); //Isn't this supposed to create a file if it doesn't detect one?
outputfile.println(contentsConverted);
outputfile.close();
}
}
}
Change the method as
public static void main(String[] args) throws Exception
I have been trying to get 2,3,4 words of a file and this is the code so far. But I am getting some error messages. Can anybody help me please? This is the code:
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
class PrintLines{
public static void main(String[] args) throws FileNotFoundException {
Scanner me = new Scanner(System.in);
System.out.print("File Name: ");
String s = me.next();
File inFile = new File(s);
Scanner in = new Scanner(inFile);
while(in.hasNextLine()){
String[] split=in.split(" ");
System.out.println(split[2]+split[3]+split[4]);
}
in.close();
}
}
But this is the error messages I am getting:
PrintLines.java:18: cannot find symbol
symbol : method split(java.lang.String)
location: class java.util.Scanner
String[] split=in.split(" ");
^
1 error
You are calling split on the Scanner itself; you should be calling it on the nextLine which returns the next line as a String:
String[] split = in.nextLine().split(" ");
If you read the docs then Scanner doesn't have a "split" method, so what you're getting is a compiler error telling you that you're calling a non-existent method.
Try swapping
String[] split=in.split(" ");
for:
String[] split=in.nextLine().split(" ");
The connection between the two methods is hinted at if you read the JavaDoc for hasNextLine(), where the nextLine() method is the next one documented.