2017-03-16 71 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

你当然是对的。但是,改善您的格式。很难说你想表达什么。 –

相关问题