我必须阅读年度最佳女演员和电影文件。然后我使用该文件创建两个新文件,一个是年份和女演员,另一个是年份和电影。该文件是这样的:如何读取文件并使用这些文件创建两个新文件?
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