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] + " ");
}
}
}
为什么循环没有达到极限?
答案 0 :(得分:0)
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