Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 926
tekknolagi Avatar asked Nov 23 '11 22:11

tekknolagi


People also ask

How do you print a string in Java?

The println(String) method of PrintStream Class in Java is used to print the specified String on the stream and then break the line. This String is taken as a parameter. Parameters: This method accepts a mandatory parameter string which is the String to be printed in the Stream.

How do you print out a variable in Java?

If we are given a variable in Java, we can print it by using the print() method, the println() method, and the printf() method.


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

like image 117
Hovercraft Full Of Eels Avatar answered Sep 19 '22 11:09

Hovercraft Full Of Eels


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.");
   }
}
like image 35
Rok Strniša Avatar answered Sep 17 '22 11:09

Rok Strniša