Java 以某种方式扫描文件中的整数

Java 以某种方式扫描文件中的整数,java,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

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

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

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);
}
字符串名;
int值;
ArrayList tempList=新的ArrayList();
while(scanner.hasNext()){
name=scanner.next();
//在这里,我试图将值赋值为2和4(仅适用于x2和x3),而不是2、3或5,因为后面跟的是-1
值=2和4
圣殿骑士。增加(价值);
}
所以在我的迭代中,如果一个名称后面跟一个数字/多个以-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

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

@maytham-ɯɐɥıλɐɯ我想设置值=2和4,因为字符串后面的整数列表不以-1结尾。最后,我会将其添加到arraylist中,但目前只设置值=2和4。@maytham-ɯɥıλɐɯ是的,因为它后面只跟1个数字,而不是以-1结尾,所以我对其进行了编辑,使其更精确clear@maytham-谢谢你。@maytham-maytham-maytham-maytham-maytham-maytham-maytham-maytham-maytham-maytham在这个例子中,它只会是x2和x3,但是如果给我一个不同的样本集,比方说x13x23x3x456-1x551,那么我只使用x1,x2和x3,因为下面的数字不以-1@maytham-谢谢,因为变量名称可以根据给定的文件进行更改。