Java - 单词中每个字母的打印量
我正在练习算法,并且我有这个问题,我必须指出单词中每个字母出现的次数。例如输入= 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
,当我进入楼层输入
考虑的StringUtils.countMatches()
的实施是正确的,问题就出在线路
System.out.print(wordArray[i] + count);
在这里,当你做wordArray[i]
,它返回一个char
。但是,在做+count
时,将该值转换为其ASCII
值,并将其加起来为count
。
要解决它,尝试做: -
System.out.print(wordArray[i] + " " + count);
太好了。谢谢。需要解释 –
首先,你应该使用countMatches(word, wordArray[i]);
但是,这不会解决整个问题。例如,你的方法会导致“f1l1o2o2r1”的输出,而对于“boohoo”这个词,你会得到“b1o4o4h1o4o4”。 如果您希望输出显示连续相同字母的数量(“b1o2h1o2”),或者如果您希望每个字母的数量(仅指定一次)按照第一次出现的顺序(“b1o4h1”),您需要重新考虑如何执行此操作“)或按字母顺序排列的字母数(”b1h1o4“)。
你当然是对的。但是,改善您的格式。很难说你想表达什么。 –
将文章输出为文字,而不是图像 –
@ChrisMowforth您的意思是什么 –