java常用类型使用作业

01、

将一批单词存入一个字符串数组中,例如:{“good”,“word”,“work”,“mean”,“thank”,“me”,“you”,“or”,“and”}

进行如下处理:

  1. 统计含有子字符串or的单词个数;

  2. 统计以字符m开头的单词个数

public class Hello2 {
	 public static void main(String a[]){
		 String str1[] = {"good","word","work","mean","thank","me","you","or","and"};
		 int i = 0;
		 int m = 0,n = 0;
		 //str1.length = 1
		 for(i=0; i< str1.length; i++) {
		 //如果不含有字符串 or,那么indexof返回 -1
			 if(str1[i].indexOf("or") != -1)
			 	 m++;	
			 if(str1[i].startsWith("m"))
			 	n++;	
		 }
		 System.out.printf("含有字符串or的单词个数:%d\n", m);
		 System.out.printf("以字符m开头的单词个数:%d\n", n);

  }
}

输出结果:
在这里插入图片描述

函数拓展:indexOf和startWith

indexOf() 方法有以下四种形式:
public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

startsWith() 方法用于检测字符串是否以指定的前缀开始。返回true或false。

02、

将一批英文单词存入一个字符串数组中,例如: {“we”,“who”,“word”,“these”,“do”,“what”,“new”,“the”,“hello”}
求所有单词的平均长度,输出结果精确到小数点后2位。

public class Hello2 {
	 public static void main(String a[]){
		 String str1[] = {"we","who","word","these","do","what","new","the","hello"} ;
		 int i = 0;
		 double aver = 0.0;
		 //str1.length = 9
		 for(i=0; i< str1.length; i++) {
			 aver += str1[i].length();
		 }
		 aver = aver/str1.length;
		 System.out.printf("含有字符串or的单词个数:%.2f\n", aver);

  }
}

输出结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值