用Java打印字符串变量 [英] 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]
这有点奇怪。发生了什么以及如何打印 s的值
?
Which is sort of weird. What's happening and how do I print the value of s
?
推荐答案
您将获得Scanner对象本身返回的 toString()
值,这不是您想要的,也不是您使用Scanner对象的方式。您想要的是通过 Scanner对象获得的数据。例如,
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.
编辑
请看这里:扫描仪教程
另外看看扫描仪API ,它将解释Scanner方法和属性的一些细节。 。
Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.
这篇关于用Java打印字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!