2011-11-23 132 views
11

运行(看似简单)的代码时,我收到了一些奇怪的输出。下面是我有: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的值?

回答

20

您将获得Scanner对象本身返回的toString()值,这不是您想要的值,也不是您如何使用Scanner对象。你想要的是通过 Scanner对象获得的数据。例如,

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

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

编辑
请看这里:Scanner tutorial

也有看看Scanner API这将解释一些扫描仪的方法和属性的细节问题。

2
input.next(); 
String s = input.toString(); 

将其更改为

String s = input.next(); 

可能这就是你想干什么。

2

这是更容易得到你想要的东西:

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

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

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

您还可以使用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."); 
    } 
} 
+2

为什么要使用一个BufferedReader代替扫描仪的?使用扫描仪对象有什么问题? –

+0

@HovercraftFullOfEels确实。我重申了我的答案,以反映这只是另一种选择。 –

+0

同意。 up-vote 1+ –