Java中打印字符串变量
运行(看似简单)代码时,我得到一些奇怪的输出。这就是我所拥有的:
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);
}
}
编译成功后得到的输出是:
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
的值?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您得到的是 Scanner 对象本身返回的
toString()
值,这不是您想要的,也不是您使用 Scanner 对象的方式。您想要的是 Scanner 对象获取的数据。例如,请阅读有关如何使用它的教程,因为它将解释所有内容。
编辑
请查看此处:扫描仪教程
另请查看 < a href="http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html" rel="noreferrer">Scanner API 它将解释一些细节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,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.
您还可以使用 BufferedReader:
You could also use BufferedReader:
将其更改为
也许这就是您想要做的。
change it to
May be that's what you were trying to do.
这更有可能让你得到你想要的:
This is more likely to get you what you want:
您打印了错误的值。相反,如果您打印扫描仪对象的字符串。试试这个
You are printing the wrong value. Instead if the string you print the scanners object. Try this
如果您已尝试了所有其他答案,但仍然无效,您可以尝试跳过一行:
If you have tried all the other answers, and it still hasn't work, you can try skipping a line: