我正在尝试使用substring获取男性和女性的数量。但在本例中,我创建了 2 个类,并使用扫描仪输入我想要的记录数。如何组合for 循环中的计数?我已经得到了M和F的计数,但它没有得到我的预期输出。我尝试删除 for 循环,仅删除 for 循环,但它需要处于循环中,否则可能会出错。如果我再次放置 for 循环,它会起作用,但它被分开“它在输出框上”。如果我做错了请告诉我。A[i] = Output
public class Input {
String info, gender;
int resultf;
int resultm;
static Scanner in = new Scanner (System.in);
public void inputted() {
System.out.print("Enter a Gender: ");
info = in.nextLine();
gender = info.substring(0,1);
}
public void Output() {
resultm = info.length() - info.replaceAll("M", "").length();
resultf = info.length() - info.replaceAll("F", "").length();
System.out.println("Male: "+resultm);
System.out.println("Female: "+resultf);
}
}
public class Output {
static Input A[] = new Input [100];
static Scanner in = new Scanner (System.in);
public static void main (String args []) {
int i, size;
//Input
System.out.print("Enter how many record: ");
size = in.nextInt();
for (i = 0; i < size; i++) {
A[i] = new Input();
A[i].inputted();
}
System.out.println();
for (i = 0; i < size; i++) {
System.out.println("Gender: "+A[i].gender);
}
System.out.println();
//Output Section
for (i = 0; i < size; i++) {
A[i].Output();
}
}
}
输出:
Enter how many record: 2
Enter a Gender: M
Enter a Gender: F
Gender: M
Gender: F
Male: 1
Female: 0
Male: 0
Female: 1
预期输出:
Enter how many record: 2
Enter a Gender: M
Enter a Gender: F
Gender: M
Gender: F
Male: 1
Female: 1
海绵宝宝撒
哈士奇WWW
相关分类