Can use Scanner only once [duplicate] - java

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();
}

Related

Unexpected behavior of Scanner [duplicate]

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..

Getting runtime error [duplicate]

This question already has answers here:
NoSuchElementException with Java.Util.Scanner
(10 answers)
Closed 6 years ago.
I am trying to build a very basic program in java to print all the unique characters from the string but I am getting runtime error.
Input - amanda
output -amnd
import java.util.*;
class uniquechars {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("Enter a string:");
String str = inp.nextLine(); // input from user
String res="";
for (int i=0;i<str.length();i++){
int count=0;
for(int j=0;j<res.length();j++){
if(str.charAt(i)==res.charAt(j)){
count++;
}
}
if(count==0){
res = res+str.charAt(i);
}
}
System.out.println("Output string with only unique characters:"+res);
}
}
Error
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at uniquechars.main(Main.java:6)
If you are using any online tool to test your code, be sure to provide input to the program.
My guess is you are forgetting to give the input to the program while running it on an online tool.
It works on codechef.com/ide, you just have to select your programming language from the dropdown list. as shown here.

Java User input related

I want to take input form user, i am sure my code is right but it don't work at all. Please help is there any thing that i am doing wrong?
`public void edit() throws IOException {
sll.insertAfter();
System.out.println("Enter text: ");
String sen;
sen = keyboard.next();
Object obj = sen;
sll.put(obj);
}
when i execute this an error appears at this line
sen = keyboard.next();
import java.util.*;
public class Example
{
public static void main(String[] args)
{
Edit();
}
public static void Edit()
{
Scanner scan = new Scanner(System.in);
String random;
System.out.print("Please input some text: ");
random = scan.nextLine();
System.out.println("You entered: " + random);
}
}
I don't know what your main method looks like so I can only assume it's empty That being said I can tell you why your current code doesn't work based off of the information you've given us.
Your edit method is not static, and in this situation assuming you've laid out your program simillar to this it must be static as it is in my example.
You've not setup a scanner, or maybe you did outside of your edit method but failed to make it static?
Scanner scan = new Scanner(System.in);
Why are you using Object, if you want to edit the string just use a for loop and substring.
Object
If you provide us with more information, your full code and the error you're getting we can better help you!

How do I check what the user wrote in Java? [duplicate]

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

Scanner objects in methods and NoSuchElementException [duplicate]

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).

Categories