2014-12-03 533 views
0

我正在尝试使用扫描仪对象将字符串输入写入文本文件。扫描仪对象 - 分割字符串

字符串输入是电影名称。但是,如果文件名有两个单词,则扫描器对象只占第一个单词。

我需要它采取这两个词。这里是我的代码: -

Scanner new_dvd_info = new Scanner(System.in); 

System.out.println("Enter name of new film");`   
String film_name = new_dvd_info.next();   

任何人都可以摆脱任何光请吗?

+0

'扫描仪旁#()'只返回什么来*之前*空间。您应该使用'Scanner#nextLine'来代替整行,然后使用'String#split'。 – Maroun 2014-12-03 09:05:56

回答

5

new_dvd_info.next()替换为new_dvd_info.nextLine()以获取整条生产线。

1

Scanner.next()方法的文档说

Finds and returns the next complete token from this scanner. 
A complete token is preceded and followed by input that matches 
the delimiter pattern. This method may block while waiting for input 
to scan, even if a previous invocation of {@link #hasNext} returned 
<code>true</code>. 

所以它只是拿起直到发现“”在你的情况下,分隔符。你可以使用扫描仪上的下一行的方法来获取整个字符串new_dvd_info.nextLine()或者你可以只遍历这样的:

while(scanner.hasNext) { 
     //append to string using scanner.next(); 
} 
0

这里的问题是,你正在使用new_dvd_info.next()返回第一个完整标记。如果遇到任何分隔符(如space),它会将下一个单词视为单独的标记。

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

在上面的代码,如果你给电影作为Age of Ultron的名字就会返回你刚才令牌Age因为有令牌岁以后的分隔符。

如果您想通过分隔符分隔完整String你应该使用

Scanner sc=new Scanner(System.in); 
String s=sc.nextLine(); 
System.out.println(s); 

这会给你所需的输出即Age of Ultron