所以基本上我試圖從正在讀取的檔案中只獲取整數值,我想將每個值存盤在它自己的 ArrayList 中。
讀取檔案的資料格式如下
1002 53 1 82 169 120 80 237.6 239.0 177.6 42.5 885.8 7.4
1004 53 1 83.7 169 110 70 160.2 173.4 115.8 44.0 73.5 8.2
1006 48 1 81.1 158 130 70 102.6 173.4 100.4 61.8 73.5 5.2
ETC...
這是我的代碼:
public class Test {
public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList();
ArrayList<Double> doubleArrayList = new ArrayList();
String filePath = "records.txt";
try { // Methodology Store in string, split on spaces, covert to int or double,
// add to the variables directly from the Arraylist.
Scanner input = new Scanner(new File(filePath));
Integer integerVal = 0;
Double doubleVal = 0.0;
while (input.hasNextLine() ) {
integerVal = input.nextInt();
if (integerVal instanceof Integer) {
integerArrayList.add(integerVal);
}
doubleVal = input.nextDouble();
if (doubleVal instanceof Double) {
doubleArrayList.add(doubleVal);
}
}
System.out.println(integerArrayList);
System.out.println(doubleArrayList);
} catch (IOException e) {
e.printStackTrace();
}
}
}
我嘗試逐步除錯,問題是它按預期將每個值存盤在兩個變數中,直到達到雙精度值...
最后一個可執行步驟:

輸出例外:

如果您有任何其他解決方案/方法,請告訴我,謝謝。
uj5u.com熱心網友回復:
在使用它之前測驗下一個令牌是否是int(或)。double如果不是跳過令牌。就像是,
while (input.hasNext() ) {
if (input.hasNextInt()) {
integerArrayList.add(input.nextInt());
} else if (input.hasNextDouble()) {
doubleArrayList.add(input.nextDouble());
} else {
System.out.printf("Skipping non-numeric token: %s%n", input.next());
}
}
uj5u.com熱心網友回復:
您的意思是您只想提取 237 而不是 237.6?
int val = Math.round(Math.floor(input.nextDouble()));
您也可以使用此功能檢查下一個值
if (scanner.hasNextDouble()) { /*do double conversion*/ } else { /*just read int*/ }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485219.html
