Printing string variable in Java

I'm getting some weird output when running (seemingly simple) code. Here's what I have:

import java.util.Scanner; public class TestApplication { public static void main(String[] args) { System.out.println("Enter a password: "); Scanner input = new Scanner(System.in); input.next(); String s = input.toString(); System.out.println(s); } } 

And the output I get after compiling successfully is:

Enter a password: hello java.util.Scanner[delimiters=\p{javaWhitespace}+][position=5][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] 

Which is sort of weird. What's happening and how do I print the value of s?

6 Answers

You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,

Scanner input = new Scanner(System.in); String data = input.nextLine(); System.out.println(data); 

Please read the tutorial on how to use it as it will explain all.

Edit
Please look here: Scanner tutorial

Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.

You could also use BufferedReader:

import java.io.*; public class TestApplication { public static void main (String[] args) { System.out.print("Enter a password: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String password = null; try { password = br.readLine(); } catch (IOException e) { System.out.println("IO error trying to read your password!"); System.exit(1); } System.out.println("Successfully read your password."); } } 
2
input.next(); String s = input.toString(); 

change it to

String s = input.next(); 

May be that's what you were trying to do.

This is more likely to get you what you want:

Scanner input = new Scanner(System.in); String s = input.next(); System.out.println(s); 

You are printing the wrong value. Instead if the string you print the scanners object. Try this

Scanner input = new Scanner(System.in); String s = input.next(); System.out.println(s); 

If you have tried all the other answers, and it still hasn't work, you can try skipping a line:

Scanner scan = new Scanner(System.in); scan.nextLine(); String s = scan.nextLine(); System.out.println("String is " + s); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like