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
相关推荐
葵续浅笑16 分钟前
LeetCode - 杨辉三角 / 二叉树的最大深度
java·数据结构·算法·leetcode
wdfk_prog22 分钟前
[Linux]学习笔记系列 -- [kernel][time]timer
linux·笔记·学习
装不满的克莱因瓶25 分钟前
【Java架构师】各个微服务之间有哪些调用方式?
java·开发语言·微服务·架构·dubbo·restful·springcloud
杨筱毅32 分钟前
【穿越Effective C++】条款13:以对象管理资源——RAII原则的基石
开发语言·c++·effective c++
N 年 后37 分钟前
cursor和传统idea的区别是什么?
java·人工智能·intellij-idea
hmbbcsm1 小时前
python学习之路(六)
学习
Wu Liuqi1 小时前
【大模型学习】第一章:自然语言处理(NLP)核心概念
人工智能·学习·自然语言处理·大模型·大模型转行
CodeLongBear1 小时前
从Java后端到Python大模型:我的学习转型与规划
java·python·学习
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 94: 最长的斐波那契子序列的长度
java·数据结构·算法·leetcode·深度优先·动态规划
Zz_waiting.1 小时前
统一服务入口-Gateway
java·开发语言·gateway