java中遍历String字符串比较字母

import java.util.Scanner;

public class CountA{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);

String str,compare;

System.out.println("Input string: ");
str = scan.next();
System.out.println("Input compare alphate: ");
compare = scan.next();

int count = 0;

for(int i=0;i<str.length();i++){
String item = str.substring(i,i+1);
if(item == compare)
{
count++;
}

}
System.out.println();
System.out.println(str.length());
System.out.println(compare+" appearance: " + count);
}
}
似乎if中的语句没有执行,count始终不会增加

第1个回答  推荐于2017-10-06
字符串比较是.equals()不是用==于
for(int i=0;i<str.length();i++){
String item = str.substring(i,i+1);
if(item.equals(compare))
{
count++;
}

}本回答被提问者采纳
第2个回答  2016-10-21
例如第一次输入123,第二次输入1234
每次遍历拿到1 , 2 , 3去和 字符串1234比较,count一直都是0
还有字符串比较用.equals
第3个回答  2016-10-21
字符串比较用equals,数字类型的用==,for循环中的if判断的是字符串,阿门
第4个回答  2016-10-21
字符串相等不是使用==,而是使用equals(区分大小写)或equalsIgnoreCase(不区分大小写)

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网