问答详情
源自:2-4 Java 中的 String 类常用方法 Ⅱ

求大神解答

public class Demo {


public static void main(String[] args) {

// TODO Auto-generated method stub

String[] str={"abcdaabesase"};

int count=0;

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

if(str[i]=="a"){

count++;

}

}

System.out.println("a字母出现"+count+"次"); //结果什么是0次啊


}


}


提问者:皓婆子 2015-08-05 11:16

个回答

  • Perona
    2015-08-05 11:43:56
    已采纳

    因为你数组定义的时候只有一个下标,长度只是1,值是abcdaabesase。

    建议把这一行

    String[] str={"abcdaabesase"};

    改成

    String[] str={"a","b","c","d","a","a","b","e","s","a","s","e"};

    全代码

    public class HelloWorld {
        public static void main(String[] args) {
    		// 定义一个字符串
    		String[] str={"a","b","c","d","a","a","b","e","s","a","s","e"};
            int count=0;
            for(int i=0;i<str.length;i++){
                if(str[i]=="a"){
                count++;
                }
            }
            System.out.println("a字母出现"+count+"次"); //好厉害哦,4次了耶~~
    
        }
    
    }


  • 王xiaofeng
    2015-08-05 13:24:23

    String[] str={"abcdaabesase"};你这样表示是一个字符串,你可以打印一下System.out.println(str.length);只会显示1,所以你的字符串是abcdaabesase,并没有a