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
相关推荐
const_qiu7 小时前
第四章 07:4.7 本章小结
java·运维·服务器·人工智能
鶴哥只手遮天7 小时前
Spring AI 2.0.1 深度解析-第 22 章 Spring Boot 集成:自动配置、Properties 与条件装配
java·人工智能·开源
kkkkkkkkkk_Z7 小时前
新手自学嵌入式 | 学习日记:I2C总线协议、时序分析、读写流程与代码实现
学习
SEO_juper7 小时前
hreflang 审计工具:外贸多语言站谷歌SEO的隐性杀手
开发语言·人工智能·爬虫·python·seo
WJ.Polar7 小时前
final、单例类、枚举类、抽象类、接口
java·开发语言
江湖有缘7 小时前
Docker实战 | 使用Docker部署Imagor Studio图片编辑工具
java·docker·eureka
小羊没烦恼!8 小时前
C#综合揭秘——Entity Framework 并发处理详解
java·开发语言·前端·javascript·数据库·mysql·c#
艾iYYY8 小时前
【无标题】
linux·开发语言·网络·操作系统
NetX行者8 小时前
Rust 初体验:一个全栈工程师的编译器“毒打“笔记
开发语言·笔记·rust
刘 大 望8 小时前
Agent 的规划与执行范式:Plan-Execute-Replan 与 ReAct
java·python·ai·chatgpt·langchain·ai编程