我是一名新的Java程序員,我正在開發一個項目,要求我閱讀包含電影評論的文本文件。通過Arraylist搜索並排序
一旦我閱讀了文件,我被要求搜索和排序電影陣列,並返回每部電影的評論總數以及每部電影的平均評分。
我當前停留的部分正在迭代Array列表。
我正在使用一個內部和外部for循環,我似乎得到一個無限循環。
我會欣賞第二套眼睛。我一直在盯着這個項目幾天,並開始不看錯誤。
下面是代碼:
import java.io.*;
import java.util.*;
import java.lang.*;
public class MovieReviewApp {
public static void main(String[] args)
{
String strline = "";
String[] result = null;
final String delimit = "\\s+\\|\\s+";
String title ="";
//int rating = (Integer.valueOf(- 1));
ArrayList<MovieReview> movies = new ArrayList<MovieReview>();
//ArrayList<String> titles = new ArrayList<String>();
//ArrayList<Integer> ratings = new ArrayList<Integer>();
//HashMap<String, Integer> hm = new HashMap<String, Integer>();
//ListMultimap<String, Integer> hm = ArrayListMultimap.create();
try
{
BufferedReader f = new BufferedReader(new FileReader("/Users/deborahjaffe/Desktop/Java/midterm/movieReviewData.txt"));
while(true)
{
strline = f.readLine(); // reads line by line of text file
if(strline == null)
{
break;
}
result = strline.split(delimit, 2); //creates two strings
//hm.put(result[0], new Integer [] {Integer.valueOf(result[1])});
//hm.put(result[0], Integer.valueOf(result[1]));
// titles.add(result[0]);
//ratings.add(Integer.valueOf(result[1]));
MovieReview m = new MovieReview(result[0]);
movies.add(m);
MovieReview m2 = new MovieReview();
int rating = Integer.valueOf(result[1]);
int sz = movies.size();
for (int i = 0; i < sz; i++)
{
for (int j = 0; j < sz; j++)
{
m2 = movies.get(i);
if (movies.contains(m2))
{
m2.addRating(rating);
}
else
{
movies.add(m2);
m2.addRating(rating);
}
}
}
movies.toString();
//Collections.sort(movies);
} //end while
f.close();
//Set<String> keys = hm.keySet();
//Collection<Integer> values = hm.values();
} //end of try
catch(FileNotFoundException e)
{
System.out.println("Error: File not found");
}
catch(IOException e)
{
System.out.println("Error opening a file.");
}
} // end main
} // end class
我在打電話,所以代碼很難閱讀,但你有一段時間了。那是一個故意的無限循環嗎? – ghostbust555 2015-04-01 19:20:48
它看起來不像一個無限循環,但你確實設置了一個指數循環結構。在1,000部電影中,您將添加一百萬條評論,並且只會變得更糟。您可能想要嘗試一部分電影(如5-10),以便您可以找到代碼中的所有錯誤。 – JimW 2015-04-01 19:43:33
@DeborahJaffe我建議你快速查看一下我的答案,特別是關於使用掃描器而不是BufferedReader來獲得更高效率和更多功能的部分。關於你在Sujan Reedy A的回答中提到的問題,你可以請擴展一下嗎?我知道它沒有被正確地讀取,但是也許輸入與代碼的輸出對於找出錯誤是更有用的。 – Ungeheuer 2015-04-03 17:40:28