2016-03-02 70 views
0
之間的字符串
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class excersie2 
{ 
    @SuppressWarnings("resource") 
    public static void main(String[] args) throws FileNotFoundException 
    { 

    ArrayList<String> titles = new ArrayList<String>(); 
    ArrayList<String> titlestwo = new ArrayList<String>(); 

    String path = "C:\\Users\\T-450s\\Desktop\\showtimes.txt"; 
    File showtimes = new File(path); 

    Scanner fileReader = new Scanner(showtimes); 

    PrintWriter writer = new PrintWriter("C:\\Users\\T-450s\\Desktop\\output.txt"); 
    while(fileReader.hasNextLine()) 
    { 
     titles.add(fileReader.nextLine()); 
    } 

    String movie = ""; 
    for(String title : titles) 
    { 
     movie = title.substring((title.indexOf("\"")+1), title.lastIndexOf("\"")); 
    } 

    writer.println("\n" + movie); 
    writer.close(); 
} 
} 

讀取以下txt文件:獲取報價

Now Showing 

Title: "Deadpool" 

Duration: 1 hr 48 mins 

Title: "Zoolander" 

Duration: 1 hr 42 mins 

Title: "Kung Fu Panda 3" 

Duration: 1 hr 35 mins 

and writes a new file containing: 

Deadpool 

Zoolaner 

Kung Fu Panda 3 

如何實現這一目標?我嘗試使用子字符串,但每次都會出錯。

+0

會發生什麼沒有引號?或空行? –

+0

爲什麼你的'writer.println'在循環之外? –

+0

如何更改掃描儀的分辨率?例如scanner.useDelimiter(「\\」* \\ s +「); –

回答

2

我不確定這是否是您正在獲取的錯誤,但我認爲它是,我認爲您得到一個錯誤,因爲子字符串試圖找到一個「但不能在某些行上,因爲它不存在並導致一個錯誤,所以你可以做的是圍繞movie = substring(...用if語句來檢查「title」是否包含「,你可以這樣做,if(title.contains(" \""))也應該把writer.println放在for循環中