[英]Comparing elements in Integer list in Java
我試圖從文件中逐行讀取,然后比較該文件中的數字。
我不確定為什么程序沒有通過 if 語句執行,因為我在文件中的前兩個數字如下:
1
3
6
4
我期待increased
go 的價值,但它甚至沒有達到那個點。
public static void numComparison() throws IOException, NumberFormatException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("/Users/WorkAcc/Desktop/file.txt"));
String lines;
LinkedList<Integer> list = new LinkedList<Integer>();
int increased = 0;
while ((lines = bufferedReader.readLine()) != null){
list.add(Integer.parseInt(lines));
}
for (int i = 0; i<=list.size(); i++)
if (list.get(i) < list.get(i++)){
increased++;
}
else{
continue;
}
}
兩個簡單的更改將使您的代碼正常工作。
i++
在這種情況下不起作用。 i++
實際上改變(增加)了i
的值。 使用i+1
代替獲取新數字而不改變i
。IndexOutOfBoundsException
。這將起作用:
public static void numComparison() throws IOException, NumberFormatException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("/Users/WorkAcc/Desktop/file.txt"));
String lines;
LinkedList<Integer> list = new LinkedList<Integer>();
int increased = 0;
while ((lines = bufferedReader.readLine()) != null){
System.out.println(lines);
list.add(Integer.parseInt(lines));
}
for (int i = 0; i<list.size()-1; i++){ // -1 so you dont compare the last element of
// your list to an element that doesnt exist
if (list.get(i) < list.get(i+1)){
increased++;
}
else{
continue;
}
}
System.out.println(increased);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.