Trying to get some words out of every line - java

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.

Related

Java Scanner Error : java.util.NoSuchElementException: No line found -- java.base/java.util.Scanner.nextLine(Scanner.java:1651))

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.

What scenario would create an nosuchelementexception with nextLine()?

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.

Adding user input to Java Program

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.

Scanner input stream undefined..?

I just copied and pasted this code straight from my Uni provided lecture notes:
import java.util.*;
public class Echo {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Input a line of text");
String message = console.nextLine();
System.out.println("Your input was: "
+ message);
it keeps giving me the error: Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor Scanner(InputStream) is undefined
at Scanner.main(Scanner.java:4)
i think it is reffering to the (System.in); section of code, but I do not know how to fix it.
You named your file Scanner.java, but you should have named it Echo.java. Java requires that file names and public class names be the same.
The specific error: javac thought you were defining a Scanner class, which was conflicting with java.util.Scanner. Had you fixed that, it would have complained about the class/filename mismatch.
import java.util.Scanner;
import java.util.Scanner;
public class Echo {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Input a line of text");
String message = console.nextLine();
System.out.println("Your input was: "
+ message);

regext copying second, third and fourth word

I am trying to get the 2nd, 3rd, and 4th word from a file into another file, so far I know how to read a file and I have been trying different things but I don't get it right the code to get the words. This program will read the file.
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 line = in.nextLine();
System.out.print(line + "\n");
}
in.close();
}
}
I have tried:
int i=0;
while(!Character.isDigit(in.charAt(i))){
i++;
}
to skip the first numbers, and then get the next three words, but I don't get it right:
986 Nasir 829 0.0040 Janine 1352 0.0069
I would appreciate any advice. Thank you
You can use String.split method
String[] split = line.split(" "); // split by space
System.out.println(split[1] + split[2] + split[3]); // watch out for the array's bounds

Categories