gpt4 book ai didi

java - 如何修复计算java中子字符串的出现次数

转载 作者:行者123 更新时间:2023-12-02 00:37:06 24 4
gpt4 key购买 nike

我正在尝试使用子字符串获取男性女性的数量。但在本例中,我创建了 2 个类,并使用扫描仪输入我想要的记录数。如何在for 循环中合并计数?我已经得到了 MF 的计数,但它没有得到我的预期输出。我尝试删除 for 循环,仅删除 A[i] = Output 但它需要位于循环中,否则可能会出错。如果我再次放置 for 循环,它会起作用,但它被分开“它在输出框上”。如果我做错了请告诉我。


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();
//Print
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

最佳答案

你必须在主函数中计算它,而不是在输入类中。

public class Input {
//add functions below
public boolean IsMale(){return resultm == 1;}
public boolean IsFemale(){return resultf == 1;}

//another way without boolean
public int GetMaleCount(){return resultm;}
public int GetFemaleCount(){return resultf;}
}

将 main 中的输出部分更改为以下内容:

int male = 0;
int female = 0;
for (i = 0; i < size; i++) {
//if(A[i].IsMale()){male ++;}
//if(A[i].IsFemale()){female ++;}
//another way without boolean
male += A[i].GetMaleCount();
female += A[i].GetFemaleCount();
}
System.out.println("Male: "+male);
System.out.println("Female: "+female);

关于java - 如何修复计算java中子字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57966267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com