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

我正在尝试使用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();

        //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


蓝山帝景
浏览 106回答 2
2回答

海绵宝宝撒

您必须在主函数中对其进行计数,而不是在输入类中进行计数。public class Input {&nbsp; //add functions below&nbsp; public boolean IsMale(){return resultm == 1;}&nbsp; public boolean IsFemale(){return resultf == 1;}&nbsp; //another way without boolean&nbsp; public int GetMaleCount(){return resultm;}&nbsp; public int GetFemaleCount(){return resultf;}}将 main 中的输出部分更改为以下内容:int male = 0;int female = 0;for (i = 0; i < size; i++) {&nbsp; //if(A[i].IsMale()){male ++;}&nbsp; //if(A[i].IsFemale()){female ++;}&nbsp; //another way without boolean&nbsp; male += A[i].GetMaleCount();&nbsp; female += A[i].GetFemaleCount();}System.out.println("Male: "+male);System.out.println("Female: "+female);

哈士奇WWW

在最后一个循环中,main您Input.Output根据数组的大小调用了基数,并在该方法上打印了性别。更改Input.Output打印数据的方式。尝试添加检查if以检查您的打印是男性还是女性。或者只是改变打印结果的逻辑。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java