gpt4 book ai didi

java - 在Java中计算字符串中的字符

转载 作者:行者123 更新时间:2023-12-01 06:43:10 27 4
gpt4 key购买 nike

请问我能得到一些帮助吗?非常感谢:

我想计算一行中 * 的数量。当我尝试编译下面的代码时

    import java.util.Scanner;
/**
* Write a description of class StarCount here.
*
* @author Damon
* @version (a version number or a date)
*/
public class StarCount {

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int starCount = 0;
String input = keyboard.nextLine();
while(!input.equals("#")){

for(starCount=0; starCount<=input.length(); starCount++){
if (input.charAt(starCount).equals('*')){
System.out.println(starCount);
}//if
}//for

}//while

} //main

} // class StarCount

但是它出现了

"char cannot be dereferenced"

过去 1.5 个小时我都花在这上面了,但我还是卡住了。

如有任何帮助,我们将不胜感激。

最佳答案

顾名思义,charAt 返回一个 char,因此您需要使用 == 来比较原语

 if (input.charAt(starCount) == '*') {

关于java - 在Java中计算字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35737337/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com