How to make multiple Scanners with the same input line?
One scanner is enough.
String input1 = User.next();
String input2 = User.next();
enter this values separated by space example you entered Hello World
.
the Hello
goes to input1
then the World
goes to input2
Multiple Scanner Inputs (Java)
You don't need multiple scanners. one is more than enough
By an input like 1 3 5
you can read that as a whole line(string)
Scanner sc = new Scanner(System.in);
String input1 = sc.nextLine();
System.out.println(input1);
or just get integer by integer
int inputA1 = sc.nextInt();
int inputA2 = sc.nextInt();
int inputA3 = sc.nextInt();
System.out.println("--------");
System.out.println(inputA1);
System.out.println(inputA2);
System.out.println(inputA3);
Should a Scanner only be instantiated only once? if that's the case why so?
There are actually two separate things going on here.
You should create one
Scanner
per input source. For example, oneScanner
for each distinct input file, one forSystem.in
, one for each distinct socket input stream.The reason is (as Chrylis points out) is that various methods of
Scanner
read ahead on the scanner's input source. If the characters are not consumed by the operation, they are not put back into the input source. Rather they are buffered by theScanner
, and kept for the nextScanner
operation to use. So if you have two Scanners trying to read from the same input source, one may steal input intended for the other.This is the real reason why opening multiple
Scanner
objects onSystem.in
is bad. Not the "redundancy" argument that you proposed. There is nothing fundamentally wrong with a bit of redundancy ... especially if it simplifies the application. But scanners competing for input may result in unexpected behavior / bugs.The second problem is that when you
close()
aScanner
that also closes the input source.In your case that means that you are closing
System.in
. And then you are creating a secondScanner
to read from the (now closed)System.in
.When you attempt to us a
Scanner
to read from a closedSystem.in
, that leads to aNoSuchElementException
.
So if you hadn't called close()
on the first Scanner
, your code might have worked, but that would depend on the sequence of operations you made on the first Scanner
.
People are saying
Scanner
ain't cloneable.
They are correct.
Cannot use multiple Scanner objects in Java
There's a couple of problems here.
First, you do not want to close the System.in
stream. Other parts of the program may be using it, and you don't want to interfere with their normal operation.
Second, there's no benefit to creating more than one Scanner object. It's simply reading input from a stream, and having more than one reference to that stream isn't necessary or beneficial to your operations.
To that end, the fix to this would be straightforward:
- Use only one instance of the Scanner attached to
System.in
, and - Remove the
close()
method call.
How to use multiple scanners of different types in java?
Try this.Your code has no problem but after you can run this may be it will help you
import java.util.*;
public class Answer {
public static void main(String[] args) {
String name = "";
System.out.printf("Name of the Story Arc: ");
Scanner in = new Scanner(System.in);
if(in.hasNext()) {
name = in.nextLine();
}
int l = 0;
System.out.printf("Length of the Story Arc: ");
if(in.hasNextInt()) {
l = in.nextInt();
}
System.out.println("Name of the Story Arc: "+name);
System.out.println("Length of the Story Arc: "+l);
}
}
how to use two scanners on one method
This:
try (Scanner scanner = new Scanner(System.in)) {
// ...
}
is a try-with-resources block. When the block finishes executing, it will call scanner.close()
.
The problem with that, for your use case, is that the Scanner, in turn, invokes System.in.close()
. Once a stream has been closed, you can't read from it again, so you will get an exception when you try to create another Scanner reading from System.in
subsequently.
The most trivial fix to your code is to merge the two try-with-resources blocks, and reuse the same Scanner, so you don't close it in between. There is no good reason to have two separate scanners anyway.
But actually, you shouldn't be using try-with-resources at all.
The general rule is not to close a stream that you don't own, which roughly translates to don't close a stream you didn't open, given that Java has no concept of "ownership". You didn't open System.in
, the JVM did.
You don't know what else in your program is relying on it continuing to be open. If you do close such a stream, you mess up the state of the stream for future readers of the stream.
Now, you may think that you need to use twr, because your IDE flags a resource leak warning on the Scanner otherwise. In general, you may want to close a Scanner; in this specific case, you do not. Ignore (or suppress) that warning, if that is why you are using twr.
Related Topics
Building Executable Jar with Maven
Java Dynamic Binding and Method Overriding
What Objects How to Inject Using the @Context Annotation
How to Compile a Java File with a Different Name Than the Class
Jsch Algorithm Negotiation Fail
Get Only Part of an Array in Java
Clean Way to Combine Multiple Jars? Preferably Using Ant
Difference Between Generic Type and Wildcard Type
Java: "Final" System.Out, System.In and System.Err
Randomly Select an Item from a List
Difference in System. Exit(0) , System.Exit(-1), System.Exit(1 ) in Java
How to Generate the JPA Entity Metamodel
Java.Util.Zip.Zipexception: Error in Opening Zip File