2017-03-16 70 views
-1

我正在練習算法,並且我有這個問題,我必須指出單詞中每個字母出現的次數。例如輸入= floor,輸出= f1l1o2r1。我有以下代碼:Java - 單詞中每個字母的打印量

public static void main(String[] args) {// TODO code application logic here 
     Scanner inword = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 

     System.out.println("Enter word"); 
     String word = inword.nextLine(); 

     int length = word.length(); 
     char[] wordArray = word.toCharArray(); 
     for(int i = 0; i<length; i++){ 
      int count = StringUtils.countMatches(word, String.valueOf(wordArray[i])); 
      System.out.print(wordArray[i] + count); 
     } 
    } 

,而是我得到這個作爲輸出:103109113113115,當我進入樓層輸入

+0

將文章輸出爲文字,而不是圖像 –

+0

@ChrisMowforth您的意思是什麼 –

回答

0

考慮的StringUtils.countMatches()的實施是正確的,問題就出在線路

System.out.print(wordArray[i] + count); 

在這裏,當你做wordArray[i],它返回一個char。但是,在做+count時,將該值轉換爲其ASCII值,並將其加起來爲count

要解決它,嘗試做: -

System.out.print(wordArray[i] + " " + count); 
+0

太好了。謝謝。需要解釋 –

1

你的問題是,你打印出來的字符的ASCII碼值。嘗試

System.out.print(wordArray[i]+"" + count); 

,而不是

System.out.print(wordArray[i] + count); 
+1

我不太明白這是如何使它工作,但它確實能解決我的問題。謝謝 –

+1

如果您願意,您可以upvote我的答案或標記是解決方案;) – Markus

+1

不會產生他說他期望的答案 - 稍後查看我的答案 – FredK

1

首先,你應該使用countMatches(word, wordArray[i]);但是,這不會解決整個問題。例如,你的方法會導致「f1l1o2o2r1」的輸出,而對於「boohoo」這個詞,你會得到「b1o4o4h1o4o4」。 如果您希望輸出顯示連續相同字母的數量(「b1o2h1o2」),或者如果您希望每個字母的數量(僅指定一次)按照第一次出現的順序(「b1o4h1」),您需要重新考慮如何執行此操作「)或按字母順序排列的字母數(」b1h1o4「)。

+0

你當然是對的。但是,改善您的格式。很難說你想表達什麼。 –

相關問題