使用 charAt 方法时出现“未定义 Stringchar 类型的方法 charAt(int)”

package Collections;


import java.util.HashSet;

import java.util.Iterator;

import java.util.LinkedHashSet;


public class Stringchar {


    public static void main(String[] args) {


        int count =0;

        String s = "mmamma";


        //System.out.println(s.length());


        LinkedHashSet<Character> ch = new LinkedHashSet<Character>(); 

        for (int i=0; i<s.length(); i++){

            ch.add(s.charAt(i));

        }


        Iterator<Character> iterator = ch.iterator();

        while(iterator.hasNext()){


            Character st = (Character) iterator.next();

            for (int k=0; k<s.length() ; k++){

                if(charAt(k)==  st){ // Why this charAt method is not working?   

                    count = count+1;

                }


                if(count>1) {

                    System.out.println("Occurance of "+ st + "is" + count);

                }

            }                           

        }           

    }

}

我是编码新手,所以问这个问题可能很愚蠢。我已经编写了一个代码,我试图在其中使用集合打印字符串中一个字符的出现次数和相同次数,但是我在这样做时遇到了一些问题。请求你帮忙。


陪伴而非守候
浏览 327回答 3
3回答

一只名叫tom的猫

这里:charAt(k);基本上是一样的this.charAt(k);换句话说:您正试图在此代码所在的类上调用一个方法。我假设你打算这样做someStringVariable.charAt(k)!(当然,你的意思是s.charAt(),但它s是一个可怕的,没有任何意义的变量名称。你的变量是你的宠物,给它们起个有意义的名字!)

呼唤远方

你必须像这样更正你的代码,while (iterator.hasNext()) {&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; Character st = (Character) iterator.next();&nbsp; &nbsp; for (int k = 0; k < s.length(); k++) {&nbsp; &nbsp; &nbsp; &nbsp; if (s.charAt(k) == st) { // Why this charAt method is not working?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if (count > 1) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Occurance of " + st + " is: " + count);&nbsp; &nbsp; }}charAt方法在String类中可用,因此您必须在String引用上调用它。我也对代码做了一些改进。在while循环内声明计数变量,这样不容易出错。最后请注意,我已将if语句从for循环中移开,因为如果将其保留在for循环内,则会产生一些虚假的中间结果。

当年话下

问题是你试图在一个字符的位置获取一个字符。创建变量时,st它是一个字符,长度为 1;因此你无法到达charAt(index)那里。此外,这种使用 的方法LinkedHashSet将不起作用,因为当您将这些字符添加到 时,LinkedHashSet它不会多次添加每个字符。相反,您想要一个ArrayList.这可能不是最有效的解决方案,但它会完成您尝试使用 HashSetString s = "mmamma";List<Character> characterList = new ArrayList<>();LinkedHashSet<Character> characterLinkedHashSet = new LinkedHashSet<>();for(char c : s.toCharArray()) {&nbsp; &nbsp; characterLinkedHashSet.add(c);&nbsp; &nbsp; characterList.add(c);}for (Character character : characterLinkedHashSet) {&nbsp; &nbsp; int frequency = Collections.frequency(characterList, character);&nbsp; &nbsp; System.out.println("The frequency of char " + character + " is " + frequency);}&nbsp; &nbsp; &nbsp;因此,它的作用是创建您的LinkedHashSet以及ArrayList. 在ArrayList所有的字符店Collection和LinkedHashSet专卖店只有每个字符的一个实例。然后我们可以循环HashSet并获取内部的频率ArrayList
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java