java 正则表达式循环 运行 不正确

java regex loop are not running properly

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringInteger {

    public static void main(String[] args) {
        System.out.println("Enter no. of times input numbers will be given : ");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int index = 0, index1 = 0;
        int girl[] = new int[1000];
        int boy[] = new int[1000];
        for (int i = 1; i <= n; i++) {
            String s = sc.next();
            Pattern mypattern = Pattern.compile("[0-9]+");
            Matcher mymatcher = mypattern.matcher(s);
            while (mymatcher.find()) {
                if (i % 2 != 0) {
                    girl[index] = Integer.valueOf(mymatcher.group());
                    index++;
                } else {
                    boy[index1] = Integer.valueOf(mymatcher.group());
                    index1++;
                }
            }
        }
        for (int j = 0; j < index; j++) {
            System.out.print(girl[j] + " ");
        }
    }
}

为什么循环未运行达到其极限?

对于 no. 循环正确运行。次即 n.

你应该格式化你的代码,Java class 名称应该是 CamelCase 并且没有下划线,并且添加 System.out.println 以帮助你理解调试和程序更合乎逻辑。

您的程序似乎需要一个用户可以输入数字的数字。

有 2 个数组,即女孩和男孩。如果数字是奇数则将其添加到女孩数组,如果数字是偶数则将其添加到男孩数组。

女孩数组终于打印出来了。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringInteger {

    public static void main(String[] args) {
        System.out.println("Enter no. of times input numbers will be given : ");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int index = 0, index1 = 0;
        int girl[] = new int[1000];
        int boy[] = new int[1000];
        for (int i = 1; i <= n; i++) {
            String s = sc.next();
            Pattern mypattern = Pattern.compile("[0-9]+");
            Matcher mymatcher = mypattern.matcher(s);
            while (mymatcher.find()) {
                if (i % 2 != 0) {
                    girl[index] = Integer.valueOf(mymatcher.group());
                    index++;
                } else {
                    boy[index1] = Integer.valueOf(mymatcher.group());
                    index1++;
                }
            }
        }
        for (int j = 0; j < index; j++) {
            System.out.print(girl[j] + " ");
        }
    }
}

样本运行:

Enter no. of times input numbers will be given : 
4
10
11
12
13
10 12