繁体   English   中英

用Java打印字符串变量

[英]Printing string variable in 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的值?

您将获得Scanner对象本身返回的toString()值,这不是您想要的,而不是您使用Scanner对象的方式。 您想要的是Scanner对象获取的数据。 例如,

Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);

请阅读有关如何使用它的教程,因为它将解释所有。

编辑
请看这里: 扫描仪教程

另请参阅Scanner API ,它将解释Scanner方法和属性的一些细节。

您还可以使用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();

改为

String s = input.next();

可能是你想要做的。

这更有可能得到你想要的东西:

Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);

您正在打印错误的值。 相反,如果您打印扫描仪对象的字符串。 试试这个

Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);

如果您已经尝试了所有其他答案,但仍然无效,您可以尝试跳过一行:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM