【问题标题】:java regex loop are not running properlyjava 正则表达式循环没有正常运行
【发布时间】:2017-08-22 05:21:46
【问题描述】:
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] + " ");
        }
    }
}

为什么循环没有达到其极限?

【问题讨论】:

  • 你能简单描述一下这段代码应该做什么吗?
  • 还有它实际上在做什么。
  • 达到极限 ?你得到的输出是什么,你期望的输出是什么?
  • 实际上我想运行 n 次循环,我想在字符串中写一些东西,并使用正则表达式我想匹配它是否包含整数。虽然取 n=2 我不,不能用字符串写任何东西,意味着循环没有运行.....
  • @ShubhamKumar - 你试过我的解决方案了吗?

标签: java regex loops pattern-matching matcher


【解决方案1】:

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

您应该格式化您的代码,Java 类名应该是 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 

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2014-07-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多