簡體   English   中英

查找字符串中每個數字的出現次數

[英]Find number of occurences of each digit in string

僅供參考。 我堅持的另一項練習。 問題是查找字符串中每個數字的出現次數。 我覺得我已經很接近了,但是我得到了一些古怪的結果。 我是新手,因此請盡可能提供提示/幫助。 謝謝!

這是我到目前為止的內容:

import java.util.Scanner;

    public class Practice5 {
 public static void main(String[] args) {
  Scanner input= new Scanner(System.in);
  System.out.println("Enter a string");
  String s = input.next();

  int[] counts = countNumbers(s);

  String output = "";

  for (int i = 0; i < counts.length; i++) {
   if (counts[i] != 0)
                        {
           output += "Digit" + (char)('0' + i) + " appears " +
           counts[i] + ((counts[i] == 1) + " times\n");
                        }

           }

                System.out.print(output);
           }


 private static int[] countNumbers(String s) {
  int[] counts = new int[10];

  for(int i = 0; i < s.length(); i++) {
   if (Character.isDigit(s.charAt(i)));
   counts[s.charAt(i) - '0']++;
  }
  return counts;
 }
}

好。 現在,如果我輸入類似“ 23 t5t6 u76u 232 g1”的字符串

我得到:

2 appears 1 time
3 appears 1 time

這顯然是不正確的。 應該出現2次3次,出現3次2次,出現5次1次,依此類推。我們將不勝感激。

您的第一個問題是使用Java掃描器。 如果我沒記錯的話,您將只讀取第一個子字符串,直到第一個空格。 您可能想在整個字符串上運行,因此使用掃描儀不是正確的選擇。

一旦獲得了整個字符串,仍然會有問題。 您代碼中的主要問題是在讀取的行中

if (Character.isDigit(s.charAt(i)));

您在末尾有一個分號。 結果,總是執行下一行(您在其中更新值)。 這是一個問題,因為有時您的字符不是數字,因此索引“ character-'0'”可能超出了您定義的10。 Java應該抓住它來創建異常。 您沒有看到此異常,因為您的代碼只會處理第一個“ 23”

在此語句的末尾刪除分號:

if (Character.isDigit(s.charAt(i)));

您的編碼風格給您帶來了麻煩。 如果您采用一些明智的約定(例如,一致的意圖,在所有塊(如if / else和for)周圍加括號),則發現此錯誤將沒有問題。

除了其他字符提到的多余的分號外,您的輸入還包含空格(“”)字符,但是您只能讀取直到空白為止的第一組字符。 您可以使用像這樣的一行來讀取整行輸入:

String s = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)).readLine();

您將需要使用try / catch塊或將“ throws java.io.IOException”添加到您的方法中。

這對於評論來說太長了,因此我將其回答,因為我認為這很有趣並且不一定眾所周知。

為了完整起見,應注意,我可以輸入一個字符串,該字符串會使您的程序崩潰。 您正在分配一個可以容納10個整數的int [],但是您必須知道Unicode字符中的位數遠遠超過10個。

因此,您的程序應將ArrayIndexOutOfBoundsException拋出很多位數。

您可以使用以下程序根據Character.isDigit(...)打印所有數字字符(Character.isDigit(...)為整數,因此我們循環遍歷所有正整數):

  for (int i = 0; i < Integer.MAX_VALUE; i++) {
    if (Character.isDigit(i)) System.out.println(i + ": " + (char) i);
  }

在我的Java版本上,它返回268個這樣的數字(實際數字位數可能因Java版本而異,具體取決於所支持的Unicode實際版本)。

請注意,isDigit(...)不帶字符,而是一個int,它表示Unicode代碼點。

48 is a digit: 0
49 is a digit: 1
50 is a digit: 2
51 is a digit: 3
52 is a digit: 4
53 is a digit: 5
54 is a digit: 6
55 is a digit: 7
56 is a digit: 8
57 is a digit: 9
1632 is a digit: ٠
1633 is a digit: ١
1634 is a digit: ٢
1635 is a digit: ٣
1636 is a digit: ٤
1637 is a digit: ٥
1638 is a digit: ٦
1639 is a digit: ٧
1640 is a digit: ٨
1641 is a digit: ٩
1776 is a digit: ۰
1777 is a digit: ۱
1778 is a digit: ۲
1779 is a digit: ۳
1780 is a digit: ۴
1781 is a digit: ۵
1782 is a digit: ۶
1783 is a digit: ۷
1784 is a digit: ۸
1785 is a digit: ۹
etc.

我將給您另一個我創建的簡單算法:

public class Ex95 {

    public static void main(String[] args) {
        int [] counts = count("1B2A2137455");
        for (int i = 0; i < counts.length; i++) {
            System.out.println("counts of [" + i + "] is: " + counts[i]);

        }

    }
    public static int[] count(String s){
        int [] counts = new int[10];
        char [] c = s.toCharArray();
        int counter = 0;
        for(int i=0;i<counts.length;i++){
            for(int j=0;j<c.length;j++){

                    if(Character.isDigit(c[j]) && i == Character.getNumericValue(c[j])){
                        counter++;

                }
            }
            counts[i] = counter;
            counter = 0;
        }
        return counts;
    }
}

您可以使用以下代碼獲取結果,而不用檢查Character.isDigit函數:-

public static void main(String[] args){
    int[] arr = {0,1,2,3,4,5,6,7,8,9};
    String str = "abc123456";
    HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
    for (int i=0;i<10;i++){
        hm.put(arr[i], 0);
    }
    for (int i=0;i<str.length();i++){
        if(hm.containsKey(str.charAt(i) - '0')){
            hm.put(str.charAt(i) - '0', hm.get(str.charAt(i) - '0')+1);
        }
    }
    System.out.println(hm);
}

暫無
暫無

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

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