簡體   English   中英

掃描程序以某種方式遍歷文件中的整數

[英]Scanner looping through integers from file in certain manner

我只是有一個簡短的問題,關於如何在一個循環中最好地做到這一點。

如果我從以下文本文件初始化掃描儀...

x1 2 3 -1 x2 2 x3 4 x4 5 -1

我使用以下代碼:

String name;
int value;
ArrayList<Integer> tempList = new ArrayList<Integer>();

while(scanner.hasNext()) {
    name = scanner.next();
    //Over here, I'm trying to assign value to be 2 and 4 (only for x2 and x3),     not 2, 3, or 5 because it's followed by a -1
    value = 2 and 4
    tempList.add(value);
}

因此,在我的迭代中,如果名稱后跟一個以-1結尾的數字/多個數字,則不執行任何操作,但是如果名稱后接一個數字,則將value設置為number

是否需要多次遍歷文件才能知道哪些字符串以-1數字結尾?

這是一種方法

    String s = " x1 2 3 -1 x2 2 x3 4 x4 5 -1 lastone 4";

    Scanner sc = new Scanner(s);

    String currentName = null;
    int currentNumber = -1;

    while (sc.hasNext()) {

        String token = sc.next();

        if (token.matches("-?\\d+")) {
            currentNumber = Integer.parseInt(token);
        } else {
            if (currentName != null && currentNumber > -1) {
                System.out.println(currentName + " = " + currentNumber);
            }
            currentName = token;
            currentNumber = -1;
        }
    }

    if (currentName != null && currentNumber > -1) {
        System.out.println(currentName + " = " + currentNumber);
    }

輸出:

x2 = 2
x3 = 4
lastone = 4

編輯 :更正(如果存在,則打印最后一對)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM