[英]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
? 发生了什么,我如何打印
s
的值?
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. 您将获得Scanner对象本身返回的
toString()
值,这不是您想要的,而不是您使用Scanner对象的方式。 What you want instead is the data obtained by the Scanner object. 您想要的是Scanner对象获取的数据。 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. 另请参阅Scanner API ,它将解释Scanner方法和属性的一些细节。
You could also use BufferedReader : 您还可以使用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.");
}
}
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.