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

时间:2015-09-12 01:08:01

标签: java

我刚才有一个关于如何在循环的一次迭代中做到最好的问题。

如果我从以下文本文件初始化扫描仪......

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号结尾?

1 个答案:

答案 0 :(得分: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

编辑:更正(打印最后一对,如果有)