Java print string variable

When I run (seemingly simple) code, I get some strange output This is 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);
  }
}

The output after successful compilation 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]

It's a little strange What happened and how to print the value of S?

Solution

You get the toString () value returned by the scanner object itself, which is not what you want, not how to use the scanner object What you want 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, because it will explain everything

Edit here: scanner tutorial

You can also look at the scanner API, which will explain some of the finer points of scanner methods and properties

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>