简体   繁体   中英

Scanner looping through integers from file in certain manner

I just had a quick question regarding on how best to do this in one iteration of a loop.

If I initialize a scanner from the following text file...

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

I use the following code:

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);
}

So in my iteration, if a name is followed by a number/multiple numbers which end with a -1, do nothing, but if a name is followed by a number then set value = number

Would this require multiple passes through the file to know what strings end with a -1 number?

Here's one way of doing it

    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);
    }

Output:

x2 = 2
x3 = 4
lastone = 4

EDIT : correction (printing the last pair if present)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM