Java reading from Standard in using Scanner giving wrong results [duplicate] - java

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 6 years ago.
I am using netbeans.
I am trying to read standard in or arguments using Scanner. However whenever I try to display something, I get something completely different.
Scanner input = new Scanner(System.in);
System.out.println(input);
So, for example if the preset command line argument is "Awesome!"
I want it to print out Awesome! But I get some long gibberish such as :
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]

Here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream. you can use following methods of Scanner class (for your case its string) :
nextInt to input an integer
nextFloat to input a float
nextLine to input a string
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String user_value = in.nextLine();
System.out.println(user_value);
}

Here is the code you should use:
import java.util.Scanner;
public class InputTesting {
public static void main( String[] args ) {
Scanner input = new Scanner ( System.in );
String str1;
System.out.println("Input string: ");
str1 = input.next();
System.out.println( str1 );
}
}

Related

How to skip whitespaces and take input in Single line using Scanner

I need to take input in a single line of String which is a combination of String and integers.
I have tried to take the input like this
Scanner in = new Scanner(System.in);
String stringWithoutSpaces=in.nextLine();
But, scanner reads only the first character.
Input String:A 10,B 10,C 10,D 10
Required String:A10,B10,C10,D10
I need this input in a one single line using scanner class.
From what I understand, you are trying to receive the string from the user without storing all the white spaces. If your goal is to remove all the white spaces from the user input string, you can use replaceAll.
Code:
Scanner in = new Scanner(System.in);
System.out.print("Enter input: ");
String input = in.nextLine();
String noWhiteSpaces = input.replaceAll(" ", "");
System.out.println(noWhiteSpaces);
Console:
Enter input: A 10,B 10,C 10,D 10
A10,B10,C10,D10
import java.util.*;
public class Solution {
public static void main(String args[]) {
System.out.println("Hello world");
Scanner scanner=new Scanner(System.in);
String aItems = scanner.nextLine();
System.out.println(aItems);
}
}
This is working fine. I have Provided same input as mentioned by you and it is taking it as one string.Share your complete code or match from this one.

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

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

Java: Read from console [duplicate]

This question already has answers here:
Getting Keyboard Input
(10 answers)
Closed 8 years ago.
I'm don't know how to read from the console in Java.
If it's possible I want to do it using a scanner.
This is what i tried while learning Java.
package Scanners;
import java.util.Scanner;
public class ConsoleScanner {
static Scanner input = new Scanner(System.in);
public static void main(String[] args){
if(input.equals("Hello"))
System.out.println("You typed in: Hello ");
if(input.equals("Good Bye"))
System.out.println("You typed in: Good Bye");
else{
System.out.println("You typed in: " + input);
}
}
}
It give's me this error:
You typed in:
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match
valid=false][need input=false][source
closed=false][skipped=false][group separator=.][decimal
separator=\,][positive prefix=][negative prefix=\Q-\E][positive
suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
If there is a better way to read from the console then please post it.
- Thanks
You don't want to print the Scanner itself. You want to call the various Scanner functions to get the input. Have a look at the Scanner API and the Scanner tutorial (which are the first and second results for googling "Java Scanner") for more info.
Try this:
package Scanners;
import java.util.Scanner;
public class ConsoleScanner {
static Scanner scanner = new Scanner(System.in); //Creates the scanner
public static void main(String[] args){
String input = scanner.NextLine(); //Sets the string input equal to whatever the user types next
if(input.equals("Hello"))
System.out.println("You typed in: Hello ");
if(input.equals("Good Bye"))
System.out.println("You typed in: Good Bye");
else{
System.out.println("You typed in: " + input);
}
}
}
My friend you have to use
Scanner scanner= new Scanner(System.in);
input = scanner.next();
This method finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
import java.util.Scanner;
class ScannerDemo{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your age");
int age=sc.nextInt();
System.out.println("age:"+age);
}
}

Scanner not working? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to Java and I am trying to make a Java app where it asks you to spell "Java" and if you spelled it correctly it will type "yes", however, it is typing "no", what am I doing wrong:
package quiz;
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
Scanner kirill = new Scanner(System.in);
System.out.println(kirill.next());
String kirill2 = "Java";
if (kirill.equals(kirill2)){
System.out.println("yes");
}else{
System.out.println("no");
}
System.out.println(kirill);
kirill.close();
}
}
Running code:
Java
Java
no
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=4][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
if (kirill.equals(kirill2)){
kirill is the Scanner object, not the string. Try something like this:
Scanner kirill = new Scanner(System.in);
String userInput = kirill.next();
if (userInput.equals("Java")){
...
Also, note that your code will print "yes" if the user types "Java is a programming langauge." If you only want it to validate with just "Java," replace next with nextLine.
package quiz;
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
String kirill;
String kirill2 = "Java";
Scanner input = new Scanner(System.in);
kirill = input.next();
if (kirill.equals(kirill2)){
System.out.println("yes");
}else{
System.out.println("no");
}
System.out.println(kirill);
input.close();
}
}
Minor issue with your Scanner. You were trying to match a Scanner to a String. You can't to that silly!
Save what you're reading into a String instead of comparing the Scanner object with a String. Your main method should look something like
public static void main(String[] args) {
Scanner kirill = new Scanner(System.in);
String input = kirill.nextLine();
System.out.println(input);
String kirill2 = "Java";
if (input.equals(kirill2)){
System.out.println("yes");
}else{
System.out.println("no");
}
System.out.println(kirill);
kirill.close();
}
Also, note that .next() will only scan to the first delimiter (which is by default any whitespace), so if you want to make sure that the user only types "Java", then you should probably use .nextLine() instead of .next().
Let's take a quick look on your code, inside main():
Scanner kirill = new Scanner(System.in);
creates a scanner and assigns it to a variable, OK.
System.out.println(kirill.next());
Prints what the user types, but doesn't assign it to anything.
String kirill2 = "Java";
Just a String variable... OK.
if (input.equals(kirill2)){
If the scanner equals some text, then proceed. Hold on, you see what I just said? Comparing a Scanner and a String. This wouldn't end up right. Imagine a robot, and you give it a cup of water and a paper with "water" written on it, and ask if they are equal. Obviously they're not, and they can't be. You are comparing a set value with another set value, instead of the user's input. The following would be correct:
package quiz;
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //creates a scanner
String text = "Java"; //creates the text to be compared
String input = scan.nextLine(); //read some arbitrary text the user types
if (input.equals(text)){ //checks if user's input is equal to text
System.out.println("yes");
}else{
System.out.println("no");
}
scan.close(); //closes the Scanner
}
}
Although not required, it's a good practice to name variables after what they do or represent, or you will get confused very quickly...
So here, an easier method would be:
package quiz;
import java.util.Scanner;
public static void main(String[] args) {
String userInput;
String word = "Java":
Scanner in1 = new Scanner(System.in);
userInput = in1.next();
System.out.println( userInput );
if (word.equals(userInput)) {
System.out.println("Yes!");
}else{
System.out.println("No.");
}
System.out.println( userInput );
userInput.close();
}

Categories