簡體   English   中英

接收兩個自然數並計算其中一個在另一個中出現的次數。 爪哇

[英]Receiving two natural numbers and calculating how many times one of them appears in the other. java

我正在嘗試編寫一個從用戶那里接收兩個數字的程序。 第一個 (x) 是 0 - 9 之間的數字,第二個 (y) 是任何自然數。 問題是我想檢查 x 在 y 中的次數,例如:如果 x = 2 和 y = 2245 那么輸出將為 2

int x = 3;
int y = 233457693;

int total = 0;
String[] ys = String.valueOf(y).split("");
for (String s : ys) {
    if (s.equals(String.valueOf(x))) total++;
}
System.out.println(total);

打印 3

我的技巧是在String 中轉換int ,在使用Matcher類查找並計算字符串y 中有多少字符串x 之后。

所以,我嘗試了類似的方法,它奏效了:

int x = 2;
int y = 2245;

Pattern pattern = Pattern.compile(x + ""); //Create the pattern with the x number
Matcher matcher = pattern.matcher(y + ""); //Create the matcher wtih de pattern and insert y in string

int c = 0; 
while (matcher.find()) c++; //Count the matches

System.out.println(c); //Print

輸出:

2

這是使用 Stream 的 Java 8 及更高版本的解決方案:

int x = 2;
int y = 2245;
long count = String.valueOf(y).chars().filter(ch -> ch == Character.forDigit(x,10)).count();

您可以將 x 和 y 轉換為 String 並使用 charAt() 方法。

    int x = 2;
    int y = 2245;
    int counter = 0;

    String xString = String.valueOf(x);
    String yString = String.valueOf(y);


    for(int i=0; i<yString.length(); i++)
    {
        if(yString.charAt(i)==xString.charAt(0))
            counter++;
    }

    System.out.println(counter);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM