Java 计算给定字符串中的字符数并打印
我试图找到字符串中的字符数并打印它 例如: 输入:Java 计算给定字符串中的字符数并打印,java,string,Java,String,我试图找到字符串中的字符数并打印它 例如: 输入: aaaaaggff 输出:(未成功) 代码: for(inth=0;h
aaaaaggff
输出:(未成功)
代码:
for(inth=0;h
这里的假设是,您希望打印字符在更改之前重复的数字
您可以尝试:
public class MyClass {
public static void main(String args[]) {
String input = "aaaaaggff";
char c = input.charAt(0);
int count = 1;
System.out.print(c);
for (int i = 1; i < input.length(); i++) {
if (input.charAt(i) == c) {
System.out.print(input.charAt(i));
count++;
} else {
System.out.print(count);
System.out.print(input.charAt(i));
count = 1;
c = input.charAt(i);
}
}
// Print the count of the final character
System.out.println(count);
}
}
你的问题是什么?你试过什么?您的代码在哪里?请提供您尝试过的代码
System.out.println(“aaaaa ggff.length())
您需要编辑您的问题并告诉我们问题所在。显示您在问题中编写的代码,而不是在注释中。你已经告诉我们你期望的产量;您还需要告诉我们您得到的是什么输出。您所说的“输出(未成功)”是指“必需的输出,但代码不返回此信息”?非常感谢,您节省了我的时间。@MADHUkandukuri如果这回答了您的问题,请检查它,使其标记为已回答。是的,“我检查过它是否正常工作了。@MADHUkandukuri我的答案旁边有一个复选标记。你点击那个。
public class MyClass {
public static void main(String args[]) {
String input = "aaaaaggff";
char c = input.charAt(0);
int count = 1;
System.out.print(c);
for (int i = 1; i < input.length(); i++) {
if (input.charAt(i) == c) {
System.out.print(input.charAt(i));
count++;
} else {
System.out.print(count);
System.out.print(input.charAt(i));
count = 1;
c = input.charAt(i);
}
}
// Print the count of the final character
System.out.println(count);
}
}
aaaaa5gg2ff2