This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
In this code, throws me this exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at com.cristianvalero.filetransfers.main.client.Client.askToDo(Client.java:98)
at com.cristianvalero.filetransfers.main.client.Client.run(Client.java:64)
at com.cristianvalero.filetransfers.main.client.Client.main(Client.java:36)
Method that throws the error:
private String askToDo()
{
Scanner teclado = new Scanner(System.in);
System.out.print("What would you like to do? [help]: ");
String a = teclado.nextLine().toLowerCase();
teclado.close();
return a;
}
But in this code that executes before the other code, no throws any error.
private void setConnection() //Type of bookmarks "servers":["casa:1.1.1.1:3306", "trabajo:1.1.1.1:7809"]
{
Scanner teclado = new Scanner(System.in);
System.out.print("New server [N] or Connect previous server [P]: ");
final String typed = teclado.nextLine().toLowerCase();
if (typed.equals("n"))
noHaveServers(teclado);
else if (typed.equals("p"))
{
if (ServerList.getAllServers(CONFG).size() == 0)
noHaveServers(teclado);
else
haveServers(teclado);
}
else
{
System.out.println("Sorry, I can't understand you.");
teclado.close();
setConnection();
}
teclado.close();
}
PD: This methods are in the Client class that is extended of Thread and are called from the run() method.
Don't close the Scanner teclado in setConnection(). Closing a Scanner also closes its associated stream. Then in askToDo, when you create another Scanner, System.in is already closed.
You should have a single top-level static Scanner object, initialized with System.in, and use that everywhere in your class instead of creating a new Scanner in each method.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
NoSuchElement exception when using Scanner
(2 answers)
Closed 1 year ago.
This is a silly game written in Python, I was wondering how to reproduce it in Java:
name = ''
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')
Basically, it requests to write the string "your name" to break the while loop, now, I've tried this code in Java but it throws an error:
import java.util.Scanner;
public class sillyGame {
public static void main(String [] args) {
String name = "";
while (name != "your name"){
System.out.println("Please type your name");
Scanner input = new Scanner(System.in);
name = input.next();
input.close();
}
System.out.println("thank you");
}
}
The error is: "Exception in thread "main" java.util.NoSuchElementException"
I really appreciate your help.
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.
This question already has answers here:
Close Scanner without closing System.in
(3 answers)
Closed 2 years ago.
So my IDE is complaining if I don't enclose the Scanner in a try with block, but if I do it this way instead of closing it when it's supposed to close (once win = true), it closes the System.in stream, how do I prevent that?
public final void turn() {
System.out.println("Enter your next move!");
try (Scanner keyboard = new Scanner(System.in)) {
final String move = keyboard.nextLine();
if (move.isEmpty()) {
won = true;
return;
}
if (!validateFormat(move)) {
System.out.println("Invalid format, try again.");
return;
}
String[] moveAr;
try {
moveAr = move.split(",");
} catch (PatternSyntaxException e) {
System.out.println(e.getMessage());
return;
}
try {
validFields(moveAr);
} catch (InvalidTurnException e) {
System.out.println(e.getMessage());
return;
}
final char colour = spielFeld.getField(getColumn(moveAr[0].charAt(0)),Character.getNumericValue(moveAr[0].charAt(1)) - 1).getColour();
for (final String string : moveAr) {
final int line = Character.getNumericValue(string.charAt(1)) - 1;
final int column = getColumn(string.charAt(0));
spielFeld.cross(column,line);
final int columni = getColumn(string.charAt(0));
if (spielFeld.columnCrossed(columni)) {
points += crossedValues(string.charAt(0));
}
}
if (spielFeld.colourComplete(colour)) {
points += COLOUR_POINTS;
coloursCrossed++;
}
if (coloursCrossed >= 2) {
won = true;
}
}
System.out.println("Momentane Punkte: " + points);
}
I would recommend against having multiple Scanner objects wrapping around the same input stream. (in this case, System.in) The reason for this is because Scanners may consume and buffer data from the underlying stream. This means that in some cases data can be lost. You can read more about it in this question.
You might be able to get away with it here, in which case you should just not close the Scanner object by not wrapping it in a try-with-resources. In that case, you can suppress the warning with #SuppressWarnings("resource"). However, this is bad practice.
Instead, I'd recommend creating a single global Scanner object that wraps around System.in, and then passing it to this method as a parameter instead of creating a new scanner in each method that requires input.
how do I prevent that?
Don't close the Scanner object, i.e. don't use try-with-resources on a Scanner that is wrapping System.in.
Instead, accept the warning and hide it, since it's a special exception to the normal "resource" rules:
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
FYI: I'm using Eclipse IDE, and it "Surround with try-with-resources" is only the first option for fixing the warning:
This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 7 years ago.
I have the following Classes:
public class Human {
private String firstName;
private String lastName;
public Human(){
Scanner in = new Scanner(System.in);
System.out.println("Please enter Firstname");
setFirstName(in.nextLine());
System.out.println("Please enter Lastname");
setLastName(in.nextLine());
in.close();
}
}
And
public class Customer extends Human{
private long customerNumber;
private String customerCompanyName;
static long customerNumberCounter = 0;
public Customer(){
super();
Scanner in = new Scanner(System.in);
setCustomerNumber(customerNumberCounter);
customerNumberCounter ++;
System.out.println("Please enter Companyname");
setCustomerCompanyName(in.nextLine());
in.close();
}
}
When i call the following Main Method:
public static void main(String[] args) {
Customer aCustomer = new Customer();
System.out.println(aCustomer.giveFullName());
}
The Programm throwes the following Error:
Exception in thread "main" java.util.NoSuchElementException: No line
found at java.util.Scanner.nextLine(Unknown Source) at
customers.Customer.(Customer.java:17) at
customers.Customer.main(Customer.java:22)
I don't understand what I am doing wrong, since I can create an Object of Class Human without any problems but when I create a Customer, the Error pops up directly after entering the LastName in the Human Constructor.
I already renamed the Scanner and so on but that didn't solve the problem.
Anybody got a Solution for this?
Before read the next,you close the scanner.So it can not read the line:
public Human(){
Scanner in = new Scanner(System.in);
System.out.println("Please enter Firstname");
setFirstName(in.nextLine());
System.out.println("Please enter Lastname");
setLastName(in.nextLine());
//in.close();
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 8 years ago.
My System.out.println(info); line gives back "Model_X_Sale_2014.txt" instead of the information in the file. The first line being: "Jan 3128 1.59 3421 1.79" I'm new to splitting a string, but this problem is occuring before the string is even splitting.
Any idea what may be causing this? Thanks for the time either way. Also, is there a particular reason Eclipse wont let me use a try catch around the file stuff?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What year would you like to review?");
int year = Integer.parseInt(keyboard.nextLine());
String fileName= "Model_X_Sale_" + year + ".txt";
Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();//read one line at a time
MonthlySale_Baumbach input = new MonthlySale_Baumbach(line);
System.out.printf("\n%s %15.2f %s15.2f", input.getMonth(), input.getProfitX310(), input.getProfitX410());
}
scanner.close();
}
public class MonthlySale_Baumbach {
//variables
String month;
int X310_Units, X410_Units;
double X310_uPrice, X410_uPrice;
public MonthlySale_Baumbach(){}
public MonthlySale_Baumbach(String info){
System.out.println(info);
String[] st = info.split("\\s");
month = st[0];
X310_Units = Integer.parseInt(st[1]);
X310_uPrice = Double.parseDouble(st[2]);
X410_Units = Integer.parseInt(st[3]);
X410_uPrice = Double.parseDouble(st[4]);
}//end of constructor
}
Start by reading the documention for Scanner(String)
public Scanner(String source)Constructs a new Scanner that
produces values scanned from the specified string.
Parameters: source - A string to scan
What you probably want is Scanner(File)
public Scanner(File source) throws FileNotFoundException
Constructs a new Scanner that produces values scanned from the
specified file. Bytes from the file are converted into characters
using the underlying platform's default charset.
Parameters: source - A file to be scanned
Throws: FileNotFoundException - if source is not found