亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何修復計算java中子字符串的出現次數

如何修復計算java中子字符串的出現次數

藍山帝景 2023-08-04 19:01:08
我正在嘗試使用substring獲取男性和女性的數量。但在本例中,我創建了 2 個類,并使用掃描儀輸入我想要的記錄數。如何組合for 循環中的計數?我已經得到了M和F的計數,但它沒有得到我的預期輸出。我嘗試刪除 for 循環,僅刪除 for 循環,但它需要處于循環中,否則可能會出錯。如果我再次放置 for 循環,它會起作用,但它被分開“它在輸出框上”。如果我做錯了請告訴我。A[i] = Outputpublic 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: 2Enter a Gender: MEnter a Gender: FGender: MGender: FMale: 1Female: 0Male: 0Female: 1預期輸出:Enter how many record: 2Enter a Gender: MEnter a Gender: FGender: MGender: FMale: 1Female: 1
查看完整描述

2 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

您必須在主函數中對其進行計數,而不是在輸入類中進行計數。


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);


查看完整回答
反對 回復 2023-08-04
?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

在最后一個循環中,mainInput.Output根據數組的大小調用了基數,并在該方法上打印了性別。更改Input.Output打印數據的方式。嘗試添加檢查if以檢查您的打印是男性還是女性?;蛘咧皇歉淖兇蛴〗Y果的邏輯。



查看完整回答
反對 回復 2023-08-04
  • 2 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號