章节练习题
2017-07-18 18:12 耳朵嫁给了真正的谎 阅读(252) 评论(0) 收藏 举报package chapter7;
import java.util.Scanner;//导入输入包
public class test1 {
/**
* 用键盘输入一组长度为10的整形数组,并输出最大值和最小值,平均值
*/
public static void main(String[] args) {
final int M=10;
int a[]=new int[M];
int max,min,sum=0;
Scanner s=new Scanner(System.in);//从键盘接收
System.out.println("请输入一组整形数组:");
for(int i = 0;i<M;i++)
{
a[i]=s.nextInt();//获取
}
max=min=a[0];//遍历查找最大值和最小值,累和
for(int i=0;i<M;i++)
{
sum+=a[i];
if(a[i]>max)max=a[i];
if(a[i]<min)min=a[i];
}
System.out.println("当中最大的是:"+max);
System.out.println("当中最小的是:"+min);
System.out.println("平均值为:"+sum/M);
s.close();//关闭变量
}
}
第二题
package chapter7;
public class test2 {
/**
* 把字符串S当中的部分字符串截取出来
*/
public static void main(String[] args) {
String s=new String("ABCDEFG");
System.out.println("截取字符CD:"+s.substring(s.indexOf("C"),s.indexOf("D")+1));//此处需要注意的是substring(起始位置,终止位置)
System.out.println("截取字符B:"+s.substring(s.indexOf("B"),s.indexOf("B")+1));
System.out.println("截取字符F:"+s.substring(s.indexOf("F"),s.indexOf("F")+1));
}
}
第三题
package chapter7;
//将A1B2C3D4E5F6G7H8拆分开来,并分别存入int[]和String[]数组,
//得到的结果为[1,2,3,4,5,6,7,8]和[A,B,C,D,E,F,G,H],
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test3 {
public static void main(String[] args) {
int number[] = new int[8];
String letter[] = new String[8];
String str = "A1B2C3D4E5F6G7H8";
Matcher m = Pattern.compile("\\d").matcher(str);// \\d匹配所有的数字
Matcher d = Pattern.compile("\\D").matcher(str);// \\D匹配非数字
String s = "";
while (d.find()) {//返回目标字符串中是否包含于d匹配的子串
s += d.group();//返回上一次与d匹配的子串
// 将字符串拆分成字符数组
}
// 将字符串拆分成字符数组
letter = s.split("");//将一个字符串分割为子字符串,然后将结果作为字符串数组返回。
System.out.println();
String s1 = "";
while (m.find()) {
s1 += m.group();
}
// 将字符串s1拆分后给数组number赋值
// 将字符串拆分成字符数组
String[] str1 = s1.split("");
// 给number数组赋值
for (int j = 0; j < str1.length; j++) {
number[j] = Integer.parseInt(str1[j]);
}
// 输出字符串数组
for (String string : letter) {
System.out.print(string + " ");
}
System.out.println();
// 输出整形数组
for (int num : number) {
// 上面定义的number长度为
System.out.print(num + " ");
}
}
}
浙公网安备 33010602011771号