第五周课程总结&试验报告(三)
实验三 String类的应用实验目的掌握类String类的使用; 实验内容1.已知字符串:"this is a test of java".按要求执行以下操作:(要求源代码、结果截图。) 1)统计该字符串中字母s出现的次数。 3.已知字符串“ddejidsEFALDFfnef2357 3ed”。输出字符串里的大写字母数,小写英文字母数,非英文字母数。 1(1)实验代码:package third; public class S { public static void main(String args[]) { //输入语句 String dr="this is a test of java"; //设置计数器 int count=0; //将字符串变为字符数组 char[]c=dr.toCharArray(); //for循环查找并判断s出现次数 for(int i=0;i<c.length;i++) { if(c[i]=='s') { count++; } } System.out.println(count); } } 实验结果:1(2)实验代码:package third; public class Is { public static void main(String args[]) { String dr="this is a test of java"; int count=0; int i=0; //从0位置开始查找指定的字符串“is”位置 while(dr.indexOf("is",i)!=-1){ count++; i=dr.indexOf("is",i)+1; } System.out.println(count); } } 实验结果:1(3)实验代码:package third; public class Iss { public static void main(String args[]) { String dr="this is a test of java"; int count=0; //照指定的字符串“is”对字符串拆分 String[] a=dr.split(" "); //查找并判断作为单词单词“is”的位置 for(String s:a) { if(s.equals("is")){ count++; } } System.out.println(count); } } 实验结果:1(4)实验代码:package third; public class This { public static void main(String args[]) { String dr="this is a test of java"; //将字符串变为字符数组 char []c=dr.toCharArray(); //倒序输出字符串 for(int i=c.length-1;i>=0;i--) { System.out.print(c[i]); } } } 实验结果:2:实验代码:package third; public class Secret{ public static void main(String[] args) { String str="Zasw"; //加密 String str0=""; String str1=""; char[] chr=str.toCharArray(); for(int i=0;i<chr.length;i++) { int m=(int)chr[i]; if(chr[i]>='A' && chr[i]<='Z') { if(chr[i]>='X') { m=m+3-26; }else { m=m+3; } str0=str0+(char)m; } else { if(chr[i]>='x') { m=m+3-26; }else { m=m+3; } str0=str0+(char)m; } } System.out.println(str0); //解密 char[] chr1=str0.toCharArray(); for(int i=0;i<chr1.length;i++) { int m=(int)chr1[i]; if(chr1[i]>='A' && chr1[i]<='Z') { if(chr1[i]<='a') { m=m-3+26; }else { m=m-3; } str1=str1+(char)m; } else { if(chr1[i]<='c') { m=m-3+26; }else { m=m-3; } str1=str1+(char)m; } } System.out.println(str1); } } 实验结果:3:实验代码:package third; public class A { public static void main(String[] args) { String str="ddejidsEFALDFfnef2357 3ed"; //将字符串转换成字符,存到字符数组里面 char[] cha=str.toCharArray(); int daxie = 0,xiaoxie = 0,qita = 0; //依次取出每一个字符进行判断 for(int i=0;i<cha.length;i++) { //将字符强行转换成整数 int m=cha[i]; //如果转换的数在A到Z之间则字符为大写字母 if(m>='A'&&m<='Z' ) { daxie++; } //如果转换的数在a到z之间则字符为小写字母 else if(m>='a'&&m<='z' ) { xiaoxie++; } //其他则是非英文字母 else { qita++; } } System.out.println("大写字母数:"+daxie+"个"); System.out.println("小写字母数:"+xiaoxie+"个"); System.out.println("非英文字母数:"+qita+"个"); } } 实验结果:实验过程:第一题参照老师上课讲的以及jdk上写的String类方法,运用不同的构造或者普通方法,将字符串“this is a test of java”转换为字符数组或进行拆分等,最后输出结果。第二题稍复杂,首先将字符串拆分为单个字符,再通过for循环取出每个字符进行判断后,将字符强行转换成整数,再用if语句进行判断输出每个字母后移三位的结果。为保证无论是解密还是加密,最后输出的结果必然是一串英文字母,故限制了长度(m=m±3+26)。 课程总结:1.继承 学习总结:我的基础确实不太好,还需要花很多时间。有点跟不上老师的节奏。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |