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次啊
}
}
因为你数组定义的时候只有一个下标,长度只是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次了耶~~ } }
String[] str={"abcdaabesase"};你这样表示是一个字符串,你可以打印一下System.out.println(str.length);只会显示1,所以你的字符串是abcdaabesase,并没有a