Java语言程序设计基础篇_编程练习题*18.17 (数组中某个指定字符出现的次数)

题目:*18.17 (数组中某个指定字符出现的次数)

编写一个递归的方法,求出数组中一个指定字符出现的次数。需要定义下面两个方法,第二个方法是一个递归的辅助方法。

java 复制代码
public static int count(char[] chars, char ch)
public static int count(char[] chars, char ch, int high)

编写一个测试程序,提示用户在一行中输入一个字符列表以及一个字符,然后显示该字符在列表中出现的次数。

代码示例

编程练习题18_17CharacterCount.java

java 复制代码
package chapter_18;

import java.util.Scanner;

public class 编程练习题18_17CharacterCount {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter a string and a character: ");
		String str = input.next();
		char ch = input.next().charAt(0);
		System.out.println(count(str.toCharArray(), ch));
		input.close();
	}
	public static int count(char[] chars,char ch) {
		return count(chars, ch,chars.length-1);
	}
	public static int count(char[] chars,char ch,int high) {
		  if (high < 0) {  
	            return 0; // 基本情况:如果high小于0,返回0  
	        }  
	        int count = 0; // 局部变量来计数,避免使用静态变量  
	        if (chars[high] == ch) {  
	            count++;  
	        }  
	        return count + count(chars, ch, high - 1); // 递归调用并累加结果  
	}

}
输出结果
java 复制代码
Enter a string and a character: AAaaAAaaAAaa a
6
相关推荐
IronMurphy11 小时前
AI Agent学习day6 从 MCP 到 RAG 记忆:AI Agent 项目中的三块核心基础
人工智能·学习
sleven fung11 小时前
llama-cpp-python 本地部署入门
开发语言·python·算法·llama
头歌实践平台11 小时前
C++面向对象 - 运算符重载的应用
开发语言·c++·算法
福大大架构师每日一题11 小时前
rust 1.96.0 更新:语言、编译器、Cargo、Rustdoc、兼容性全面升级,必看完整解读
android·开发语言·rust
思麟呀11 小时前
C++11并发编程:互斥锁
linux·开发语言·c++·windows
砍材农夫11 小时前
物联网实战:Spring Boot + Netty 搭建 MQTT | MQTT 设备模拟器
java·spring boot·后端·物联网·struts·spring·netty
li星野11 小时前
RAG优化系列:基于用户反馈的检索权重调整(Feedback Loop)——让系统越用越聪明
python·学习
城管不管11 小时前
Agent——001
android·java·数据库·llm·prompt
AC赳赳老秦11 小时前
OpenClaw批量任务队列优化:解决任务堆积、执行缓慢、优先级混乱问题
java·大数据·数据库·c++·自动化·php·openclaw
GNG11 小时前
《10x Is Easier Than 2x》读书笔记
笔记·学习