gpt4 book ai didi

java - 如何使用 while 循环计算字符串中的特定字符 - Java

转载 作者:行者123 更新时间:2023-12-01 20:20:47 25 4
gpt4 key购买 nike

我对此非常陌生,虽然我能够使用 for 循环来完成此操作,但分配需要一个 while 循环。我尝试了下面的方法,但它不起作用。请帮忙!

package charcounter;

import java.util.Scanner;

public class CharCounter {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char userChar = '0';
String inputEntry = "";
String inputCharacter = "";
int foundOccurrences = 0;

System.out.print("Please enter one or more words: ");
inputEntry = in.nextLine();

System.out.print("\nPlease enter one character: ");
inputCharacter = in.next();
userChar = inputCharacter.charAt(0);

while (foundOccurrences < inputEntry.length()) {
if (userChar == inputEntry.charAt(0)) {

}

System.out.println("There is " + foundOccurrences + " occurrence(s) of " + inputCharacter + " in test.");

foundOccurrences++;
}

}

}

最佳答案

类似这样的事情:

        int i = 0;
while (i < inputEntry.length()) {
if (userChar == inputEntry.charAt(i++)) {
foundOccurrences++;
}
}
System.out.println("There is " + foundOccurrences + " occurrence(s) of " + inputCharacter + " in test.");

修复了错误

关于java - 如何使用 while 循环计算字符串中的特定字符 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44780206/

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