我必須閱讀年度最佳女演員和電影文件。然後我使用該文件創建兩個新文件,一個是年份和女演員,另一個是年份和電影。該文件是這樣的:如何讀取文件並使用這些文件創建兩個新文件?
2002 Nicole Kidman
The Hours
2003 Charlize Theron
Monster
2004 Hilary Swank
Million Dollar Baby
2005 Reese Witherspoon
Walk the Line
2006 Helen Mirren
The Queen
2007 Marion Cotillard
La Vie en Rose
2008 Kate Winslett
The Reader
2009 Sandra Bullock
The Blind Side
2010 Natalie Portman
The Black Swan
這是我到目前爲止有:
import java.io.*;
import java.util.*;
public class BestActress{
public static void main(String[] args)throws FileNotFoundException{
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(new File("BestActress.txt"));
while(reader.hasNextLine()){
int yearNumber=reader.nextInt();
String text=reader.nextLine();
actressLine(text, yearNumber);
String textt=reader.nextLine();
movieLine(textt, yearNumber);
}
}
public static void actressLine(String text, int year)throws FileNotFoundException{
PrintWriter writer = new PrintWriter(new File("YearBestActresses.txt"));
Scanner data = new Scanner(text);
while (data.hasNext()){
String actressName=data.nextLine();
writer.println(year+actressName);
writer.close();
}
}
public static void movieLine(String textt, int year)throws FileNotFoundException{
PrintWriter writer = new PrintWriter(new File("YearBestActresMovies.txt"));
Scanner data=new Scanner(textt);
while(data.hasNext()){
String movieName=data.nextLine();
writer.println(year+" "+movieName);
writer.close();
}
}
}
所創建的文件只是說去年那麼2010娜塔莉·波特曼和2010年的黑天鵝。
我不認爲掃描儀和while循環的方法actressLine和movieLine是有用的:省略。只要writer.println就足夠了。 – laune 2015-03-02 17:59:44
好點,@laune,我已經按照你的建議簡化了方法。 – jas 2015-03-02 18:08:38