阿里Java学习路线:阶段 1:Java语言基础-Java面向对象编程:第14章:综合案例:课时69:案例分析三(字符串统计)

案例分析三

编写程序,统计出字符串“want you to know one thing” 中字母 n 和字母 o 的出现次数。
对于本程序而言,最简单的操作方式就是直接在主方法里面定义一个操作,或者直接定义一个新的类进行处理。
范例:定义一个单独的处理类

class StringUtil {
	// 返回的第一个内容为字母n的个数,第二个内容为字母o的个数
	public static int [] count(String str) {
		int countData [] = new int [2] ;
		char [] data = str.toCharArray() ; // 将字符串变为字符数组
		for (int x = 0;x < data.length ;x ++ ){
			if (data[x] == 'n' || data[x] == 'N') {
				countData[0] ++ ;
			}
			if (data[x] == 'o' || data[x] == 'O') {
				countData[1] ++ ;
			}
		}
		return countData ;
	}
}

public class JavaDemo {
	public static void main(String args[]) {
		String str = "want you to know one thing" ;
		int result [] = StringUtil.count(str);
		System.out.println("字母n的个数" + result[0]);
		System.out.println("字母o的个数" + result[1]);
	}
}

以上的解决方案严格来讲只是一种顺序式的思维模式解决的,假设说现在统计的是字母o或者n的个数,那么还有可能进行各种其它统计的设计。
在这里插入图片描述

class StringUtil {
	private String content ; // 需要保存字符串
	public StringUtil(String content) {
		this.content = content ;
	}
	public String getContent() {
		return this.content ;
	}
	public String getInfo() {  // 默认的信息返回
		return this.getContent() ;
	}
}
class StringConut extends StringUtil{
	private int nCount ;
	private int oCount ;
	public StringConut(String content) {
		super(content);
		this.countChar() ; // 构造方法统计
	}
	public void countChar() {
		char [] data = super.getContent().toCharArray() ; // 将字符串变为字符数组
		for (int x = 0;x < data.length ;x ++ ){
			if (data[x] == 'n' || data[x] == 'N') {
				this.nCount ++ ;
			}
			if (data[x] == 'o' || data[x] == 'O') {
				this.oCount ++ ;
			}
		}
	}
	public int getNcount() {
		return this.nCount ;
	}
	public int getOcount() {
	return this.oCount ;
	}
	public String getInfo() {
		return "字母n的个数:" + this.nCount + "、字母o的个数:" + this.oCount ;
	}
}
public class JavaDemo {
	public static void main(String args[]) {
		StringConut sc = new StringConut("want you to know one thing") ;
		System.out.println(sc.getInfo());
	}
}

任何方案都可以,如果采用第一种方案比较直观,但是第二种方案更加适合于结构化的设计。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值