我正在嘗試從檔案中逐行讀取,然后比較該檔案中的數字。
我不確定為什么程式沒有在 if 陳述句之后執行,因為我在檔案中的前兩個數字如下:
1
3
6
4
我預計increased價值會上升,但它甚至沒有達到這一點。
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;
}
}
uj5u.com熱心網友回復:
兩個簡單的更改將使您的代碼正常作業。首先, i 在這種情況下將不起作用。您還應該更改 for 回圈的終點,否則您將始終得到 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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447980.html
