This question already has answers here:
Close a Scanner linked to System.in
(5 answers)
Closed 5 years ago.
In below code have two methods scanner1 and scanner2 in both methods new object of Scanner is created and scanning the input after that closing the Scanner by invoking close().
import java.util.Scanner;
public class TestScanner {
public static void scanner1(){
Scanner sc = new Scanner(System.in);//created object of scanner
System.out.println("Enter string :");
String input = sc.nextLine(); //scanning input
sc.close(); //closing scanner object
}
public static void scanner2(){//problem in scanner2
Scanner sc = new Scanner(System.in);//created another scanner object
System.out.println("Enter String :");
String input = sc.nextLine();//scanning object
sc.close();//closing the input
}
public static void main(String[] args) {
scanner1();
scanner2();//problem here
}
}
For scanner1 method working fine but when scanner2 method get invoked getting the below error:
Enter string : India Exception in thread "main"
java.util.NoSuchElementException: No line found Enter String : at
java.util.Scanner.nextLine(Unknown Source) at
cheggapril.TestScanner.scanner2(TestScanner.java:17) at
cheggapril.TestScanner.main(TestScanner.java:24)
Problem is why in scanner2 method scanner not able to scan the user input even in this method creating fresh one object of Scanner.
Please give some clear explanation. any ref or example will be much greatful.
The reason is quite simple, closing the 1st scanner object closes internally too the input stream which is actually being used by the second scanner
your options are: use only one scanner or close those when you are sure all of them are not required anymore..
Related
Say I have the following example code:
Scanner scan1 = new Scanner(System.in); // declaring new Scanner called scan1
int x = scan1.nextInt(); // scan for user input and set it to x
System.out.println(x); // print the value of x
scan1.close(); // closes the scanner (I don't know exactly what this does)
Scanner scan2 = new Scanner(System.in); // declaring new Scanner called scan1
int y = scan2.nextInt(); // scan for user input and set it to y
System.out.println(y); // print the value of y
I read the Oracle documentation on the Scanner class and came across this:
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
Does this mean that once a Scanner (of System.in) is closed, I will no longer be able to use System.in throughout the entire Java program? Or does it mean I will no longer be able to use it throughout the class? Or only the method? Or only its scope?
Another question I have is, is a Scanner restricted to the scope it was declared in (similar to the primitive data types)?
Yes, it does mean that System.in will be closed. Test case:
import java.util.*;
public class CloseScanner {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
scanner.close();
System.in.read();
}
}
This code terminates with
$ java CloseScanner
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:206)
at java.io.BufferedInputStream.read(BufferedInputStream.java:254)
at CloseScanner.main(CloseScanner.java:7)
Once closed, you won't be able to use System.in for the rest of your program. The fact that close() is passed through is nice because it means you don't have to maintain a separate reference to the input stream so that you can close it later, for example:
scanner = new Scanner(foo.somethingThatMakesAnInputStream());
You can do that and call .close() on the scanner to close the underlying stream.
In most cases you won't want to close System.in, so you won't want to call .close() in that case.
This question already has answers here:
Close a Scanner linked to System.in
(5 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm kinda new to java and used to write in Python. So when it comes to getting User Input I'm allways annoyed by how many lines of Code I need to perform such task. So I tried to make my own class that simplifies that process. I wanted to perform something like this:
input("This is written in the console: ")
Inside the Console:
This is written in the console: |
Here is the code so far:
public static String input(String text) {
Scanner scanner = new Scanner(System.in);
System.out.print(text);
String x = scanner.nextLine();
scanner.close();
return x;
}
When I use the class once, everything works just fine, but when I try to use it again, I get an Exception:
public static void main(String[] args) {
input("Input: ");
input("Input 2: ");
}
Output:
Input: blaaa
Input 2: Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at NumberConverter.input(NumberConverter.java:124)
at NumberConverter.main(NumberConverter.java:7)
I really don't know why that keeps happening. Please help me, thanks.
Thanks to "SomeJavaGuy" I finally got it to work:
public class NumberConverter {
private static Scanner scanner = new Scanner(System.in);
public static String input(String text) {
System.out.print(text);
String x = scanner.nextLine();
return x;
}
public static void main(String[] args) {
input("Write your Input: ");
input("Write another Input: ");
scanner.close();
}
I'm running Eclipse.
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
Scanner input = new Scanner; // Creates scanner object
System.out.println("Enter a line of text: "); // Outputs the prompt
String Line = input.nextLine(); //wait for user to enter line of text
System.out.println("You entered: " + Line); //Tells user what they entered
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor Scanner() is undefined
Syntax error, insert "( )" to complete Expression
at Input.main(Input.java:7)
You can't call a constructor without (), and you need a thing to read from. Change
Scanner input = new Scanner;
to
Scanner input = new Scanner(System.in);
Okay so, First of all, a constructor call needs parentheses, even if there are no parameters (It is still a function call)
Scanner scanner = new Scanner(); <<<
And put "System.in" inside these! System.in is an input stream, meaning a way to get input, and thats what the Scanner needs to work!
new Scanner(System.in);
It should work now, bye!
This question already has answers here:
How can I read input from the console using the Scanner class in Java?
(17 answers)
Closed 7 years ago.
I'm trying to make it so when the user writes Start the program does something, but I'm unsure of how to what the user actually wrote.
This was my first attempt at it:
import java.util.Scanner;
public class Suhwag {
public static void main (String args[]){
Scanner scanNer = new Scanner (System.in);
System.out.println("Please write \"Start\" to begin.");
String stinky = "Start";
if (stinky == scanNer);
But with this, I got the error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Incompatible operand types String and Scanner
After I saw the error, I tried to convert scanNer to a string as seen here:
import java.util.Scanner;
public class Suhwag {
public static void main (String args[]){
Scanner scanNer = new Scanner (System.in);
System.out.println("Please write \"Start\" to begin.");
String stinky = "Start";
String input = scanNer.nextLine();
if (stinky == scanNer);
But the same error message still appears. Anyone know what I could do to make it work?
You're trying to compare a Scanner object with a String object. First, you could input the string with the following line:
String myString = scanNer.next()
Then, compare it with "Start":
if ( myString.equals( "Start" ) )
{
...
}
You are comparing a String to a Scanner object.
You should use the equals method to compare String's
No need for the semi-colon after the if (see below)
In reference to your last code snippet:
if (stinky.equals(input)){
//do something
}
in the latter code area you said in your if statement:
stinky == scaNer
it should be
stinky.equals(input)
in your if statement, you compared still your scanner with ur stinky
change your if statment to this
if (input.equals(stinky)){<code here>}
your previous code didnt work because you compare a scanner with a string
This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 7 years ago.
I have really tried to find the answer through the threads but still hope to get some feed back.
The code below is bad style I think but I don't know why it shoot me a
java.util.NoSuchElementException after enter the number since I make two Scanner objects for two methods and I should be able to start a new input. And if I erase the input.close() in inputAndPrintNumber(), it works and compile correctly. I really hope to know why and how to fix it if I still use two Scanner obj and without erasing the input.close() if possible.
import java.util.*;
public class t{
public static void main(String [] args){
inputAndPrintNumber();
inputAndPrintString();
}
public static void inputAndPrintNumber(){
Scanner input = new Scanner(System.in);
String s = input.nextLine();
System.out.print(s);
input.close();
}
public static void inputAndPrintString(){
Scanner input2 = new Scanner(System.in);
int a = input2.nextInt();
System.out.print(a);
}
}
I don't even sure whether the code below is better or any better idea?
import java.util.*;
public class t{
public static Scanner input = new Scanner(System.in);
public static void main(String [] args){
inputAndPrintNumber();
inputAndPrintString();
input.close();
}
public static void inputAndPrintNumber(){
String s = input.nextLine();
System.out.print(s);
}
public static void inputAndPrintString(){
int a = input.nextInt();
System.out.print(a);
}
}
When you call scanner.close() it not only closes scanner, but also stream from which it reads data, in this case System.in. So if you are going use System.in later don't close it (if it is closed, we can't reopen it and read any data from it, hence exception).
Your second code example solves this problem because Scanner is being closed when you are sure that nothing else will be read from input stream.
BTW it seems that you mixed places where nextLine and nextInt should be invoked (nextLine seems to be more appropriate for inputAndPrintString while nextInt for inputAndPrintNumber).