简体   繁体   English

扫描程序以某种方式遍历文件中的整数

[英]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 因此,在我的迭代中,如果名称后跟一个以-1结尾的数字/多个数字,则不执行任何操作,但是如果名称后接一个数字,则将value设置为number

Would this require multiple passes through the file to know what strings end with a -1 number? 是否需要多次遍历文件才能知道哪些字符串以-1数字结尾?

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) 编辑 :更正(如果存在,则打印最后一对)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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