2014-12-03 166 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