用户工具

站点工具


zh:courses:java2025:ch05

这是本文档旧的修订版!


第五章:数组与字符串

课件

一维数组测试程序

Array1DTester.java
package cn.edu.bjut.chapter5;
 
public class Array1DTester {
	public static void main(String[] args) {
		int a[] = new int[5];
		for (int i = 0; i < a.length; i++) {
			a[i] = i;
		}
		for (int i = a.length - 1; i >= 0; i--) {
			System.out.println("a[" + i + "] = " + a[i]);
		}
 
		int[] b = new int[] { 4, 6, 8, 32 };
		for (int i = 0; i < b.length; i++) {
			System.out.println("b[" + i + "] = " + b[i]);
		}
	}
}

最大值和次最大值

MinMax.java
package cn.edu.bjut.chapter5;
 
public class MinMax {
	public static void main(String[] args) {
		int maxVal, submaxVal;
		int a[] = { 8, 50, 20, 7, 81, 55, 76, 93 };
 
		if (a[0] > a[1]) {
			maxVal = a[0];
			submaxVal = a[1];
		} else {
			maxVal = a[1];
			submaxVal = a[0];
		}
 
		for (int i = 2; i < a.length; i++) {
			if (a[i] > maxVal) {
				submaxVal = maxVal;
				maxVal = a[i];
			} else if (a[i] > submaxVal) {
				submaxVal = a[i];
			}
		}
 
		System.out.println(maxVal + "\t" + submaxVal);
	}
}

数组的增长原理

ExpandArray.java
package cn.edu.bjut.chapter5;
 
public class ExpandArray {
	static int[] expand(int[] m) {
		int[] n = new int[m.length * 2];
		for (int j = 0; j < m.length; j++) {
			n[j] = m[j];
		}
 
		return n;
	}
 
	static int[] expand2(int[] m) {
		int[] n = new int[m.length * 2];
		System.arraycopy(m, 0, n, 0, m.length);
 
		return n;
	}
 
	public static void main(String[] args) {
		int[] a = new int[] { 4, 6, 8, 32 };
		int[] b = expand(a); 
		int[] c = expand2(a); 
 
		for (int i = 0; i < b.length; i++) {
			System.out.println(b[i]);
		}
 
		for (int i = 0; i < c.length; i++) {
			System.out.println(c[i]);
		}
	}
}

数组名之间的赋值

ArrayAssignment.java
package cn.edu.bjut.chapter5;
 
public class ArrayAssignment {
	public static void main(String[] args) {
		int[] a = { 2, 5, 8, 25, 36 };
		int[] b = { 90, 3, 9 };
 
		System.out.println(a.length + "\t" + b.length);
 
		b = a;
		System.out.println(a.length + "\t" + b.length);
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " ");
		}
		System.out.println();
 
		for (int i = 0; i < b.length; i++) {
			System.out.print(b[i] + " ");
		}
		System.out.println();
	}
}

数组元素及数组名传递

ArrayPassPara.java
package cn.edu.bjut.chapter5;
 
public class ArrayPassPara {
	public static int add(int a, int b) {
		a += 5;
		b += 6;
		return (a + b);
	}
 
	public static void add(int[] a) {
		for (int i = 0; i < a.length; i++) {
			a[i] += 2;
		}
	}
 
	public static void main(String[] args) {
		int[] a = new int[] { 4, 6, 8, 32 };
 
		add(a[0], a[1]);
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);
		}
 
		add(a);
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);
		}
	}
}

对象数组

Student.java
package cn.edu.bjut.chapter5;
 
public class Student {
	private String name;
	private char gender;
	private int age;
	private double[] scores;
 
	public Student(String name, char gender, int age, double[] scores) {
		this.name = name;
		this.gender = gender;
		this.age = age;
		this.scores = scores;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public char getGender() {
		return gender;
	}
 
	public void setGender(char gender) {
		this.gender = gender;
	}
 
	public int getAge() {
		return age;
	}
 
	public void setAge(int age) {
		this.age = age;
	}
 
	public double[] getScores() {
		return scores;
	}
 
	public void setScores(double[] scores) {
		this.scores = scores;
	}
 
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(name + "\t" + gender + "\t" + age);
		for (int i = 0; i < scores.length; i++) {
			sb.append("\t" + scores[i]);
		}
 
		return sb.toString();
	}
}
ObjectArrayTester.java
package cn.edu.bjut.chapter5;
 
public class ObjectArrayTester {
	public static void modifyAge(Student stu) {
		stu.setAge(21);
	}
 
	public static void main(String[] args) {
		Student[] students = new Student[3];
 
		students[0] = new Student("li", 'F', 19, new double[] {89, 86, 69});
		students[1] = new Student("he", 'M', 18, new double[] {90, 83, 76});
		students[2] = new Student("zhang", 'M', 20, new double[] {78, 91, 80});
 
		for (int i = 0; i < students.length; i++) {
			System.out.println(students[i]);
		}
 
		modifyAge(students[0]);
		System.out.println(students[0]);
	}
}

二维数组

Matrix类

Matrix.java
package cn.edu.bjut.chapter5;
 
public class Matrix {
	private double[][] values;
	private int nrows, ncols;
 
	public Matrix(int nrows, int ncols) {
		this.nrows = nrows;
		this.ncols = ncols;
		this.values = new double[nrows][ncols];
	}
 
	public Matrix(double[][] values) {
		this.nrows = values.length;
		this.ncols = values[0].length;
		this.values = values;
	}
 
	public Matrix add(Matrix mat) {
		if (nrows != mat.nrows || ncols != mat.ncols) {
			return null;
		}
 
		double[][] newValues = new double[nrows][ncols];
		for (int i = 0; i < nrows; i++) {
			for (int j = 0; j < ncols; j++) {
				newValues[i][j] = values[i][j] + mat.values[i][j];
			}
		}
 
		return (new Matrix(newValues));
	}
 
        public Matrix substract(Matrix mat) {
		if (nrows != mat.nrows || ncols != mat.ncols) {
			return null;
		}
 
		double[][] newValues = new double[nrows][ncols];
		for (int i = 0; i < nrows; i++) {
			for (int j = 0; j < ncols; j++) {
				newValues[i][j] = values[i][j] - mat.values[i][j];
			}
		}
 
		return (new Matrix(newValues));
	}
 
	public Matrix multiplicate(Matrix mat) {
		if (ncols != mat.nrows) {
			return null;
		}
 
		double[][] newValues = new double[nrows][mat.ncols];
		for (int i = 0; i < nrows; i++) {
			for (int j = 0; j < mat.ncols; j++) {
				double sum = 0;
				for (int k = 0; k < ncols; k++) {
					sum += values[i][k] * mat.values[k][j];
				}
				newValues[i][j] = sum;
			}
		}
 
		return (new Matrix(newValues));
	}
 
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < nrows; i++) {
			for (int j = 0; j < ncols; j++) {
				sb.append("\t" + values[i][j]);
			}
			sb.append("\n");
		}
 
		return sb.toString();
	}
}

Matrix测试类

MatrixTester.java
package cn.edu.bjut.chapter5;
 
public class MatrixTester {
	public static void main(String[] args) {
		double[][] values1 = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
		double[][] values2 = { { 9, 8, 7 }, { 6, 5, 4 }, { 3, 2, 1 } };
 
		Matrix mat1 = new Matrix(values1);
		Matrix mat2 = new Matrix(values2);
 
		System.out.println("matrix1: ");
		System.out.println(mat1);
 
		System.out.println("matrix2: ");
		System.out.println(mat2);
 
		System.out.println("matrix1 + matrix2: ");
		System.out.println(mat1.add(mat2));
 
		System.out.println("matrix1 - matrix2: ");
		System.out.println(mat1.substract(mat2));
 
		System.out.println("matrix1 * matrix2: ");
		System.out.println(mat1.multiplicate(mat2));
	}
}

main方法中的参数

MainTester.java
package cn.edu.bjut.chapter5;
 
public class MainTester {
	public static void main(String[] args) {
		int[] a = new int[args.length];
 
		for (int i = 0; i < args.length; i++) {
			a[i] = Integer.parseInt(args[i]);
		}
 
		int sum = 0;
		for (int i = 0; i < a.length; i++) {
			sum += a[i];
		}
		System.out.println(sum);
	}
}

上机作业

  • 完善Matrix类,补充矩阵转置方法,以及提取特定行与特定列的方法;

【参考答案】

Matrix.java
package cn.edu.bjut.chapter5;
 
public class Matrix {
	private double[][] values;
	private int nrows, ncols;
 
	public Matrix(int nrows, int ncols) {
		this.nrows = nrows;
		this.ncols = ncols;
		this.values = new double[nrows][ncols];
	}
 
	public Matrix(double[][] values) {
		this.nrows = values.length;
		this.ncols = values[0].length;
		this.values = values;
	}
 
	public Matrix add(Matrix mat) {
		if (nrows != mat.nrows || ncols != mat.ncols) {
			return null;
		}
 
		double[][] newValues = new double[nrows][ncols];
		for (int i = 0; i < nrows; i++) {
			for (int j = 0; j < ncols; j++) {
				newValues[i][j] = values[i][j] + mat.values[i][j];
			}
		}
 
		return (new Matrix(newValues));
	}
 
	public Matrix substract(Matrix mat) {
		if (nrows != mat.nrows || ncols != mat.ncols) {
			return null;
		}
 
		double[][] newValues = new double[nrows][ncols];
		for (int i = 0; i < nrows; i++) {
			for (int j = 0; j < ncols; j++) {
				newValues[i][j] = values[i][j] - mat.values[i][j];
			}
		}
 
		return (new Matrix(newValues));
	}
 
	public Matrix multiplicate(Matrix mat) {
		if (ncols != mat.nrows) {
			return null;
		}
 
		double[][] newValues = new double[nrows][mat.ncols];
		for (int i = 0; i < nrows; i++) {
			for (int j = 0; j < mat.ncols; j++) {
				double sum = 0;
				for (int k = 0; k < ncols; k++) {
					sum += values[i][k] * mat.values[k][j];
				}
				newValues[i][j] = sum;
			}
		}
 
		return (new Matrix(newValues));
	}
 
	public Matrix transpose() {
		double[][] newValues = new double[ncols][nrows];
 
		for (int i = 0; i < nrows; i++) {
			for (int j = 0; j < ncols; j++) {
				newValues[j][i] = values[i][j]; 
			}
		}
 
		return (new Matrix(newValues)); 
	}
 
	public Matrix getColumn(int idx) {
		if (idx < 0 || idx >= ncols) {
			return null; 
		}
 
		double[][] colVector = new double[nrows][1];
		for (int i = 0; i < nrows; i++) {
			colVector[i][0] = values[i][idx]; 
		}
 
		return new Matrix(colVector); 
	}
 
	public Matrix getRow(int idx) {
		if (idx < 0 || idx >= nrows) {
			return null; 
		}
 
		double[][] rowVector = new double[1][ncols];
		for (int j = 0; j < ncols; j++) {
			rowVector[0][j] = values[idx][j]; 
		}
 
		return new Matrix(rowVector); 
	}
 
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < nrows; i++) {
			for (int j = 0; j < ncols; j++) {
				sb.append("\t" + values[i][j]);
			}
			sb.append("\n");
		}
 
		return sb.toString();
	}
}
  • 写一个类CharCounter,当给定一个字符串时,可以统计其中英文字母及数字出现的频次,并且可以查询特定字符出现在的频次;

【参考答案】

CharCounter.java
package cn.edu.bjut.chapter5;
 
public class CharCounter {
	private int[] count; 
 
	public CharCounter(String str) {
		this.count = new int[26 + 10];
 
		str = str.toLowerCase(); 
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
 
			if (c >= 'a' && c <= 'z') {
				int idx = c - 'a';
				count[idx]++;
			} else if (c >= '0' && c <= '9') {
				int idx = c - '0' + 26;
				count[idx]++;
			}
		}
	}
 
	public int getCount(char ch) {
		if (ch >= 'a' && ch <= 'z') {
			int idx = ch - 'a';
			return count[idx];
		} else if (ch >= '0' && ch <= '9') {
			int idx = ch - '0' + 26;
			return count[idx];
		}
 
		return -1; //无效字符
	}
 
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder(); 
 
		for (int i = 0; i < count.length; i++) {
			if (count[i] == 0) {
				continue;
			}
 
			char c = (i < 26) ? (char) (i + 'a') : (char) (i - 26 + '0');
			sb.append(c + ": " + count[i] + "\n"); 
		}
 
		return sb.toString(); 
	}
 
	public static void main(String[] args) {
		String str = "abcBCD.-,1234321我们";
 
		CharCounter counter = new CharCounter(str); 
		System.out.println(counter); 
 
		// 也可以直接得到某个字符出现的频次
		System.out.println("a: " + counter.getCount('a')); 
	}
}
  • 给定五篇专利文献,每篇专利文献的信息见下表,在上次课程作业的基础上,将这五篇专利文献存放在数组中。
专利申请号(Application No) 申请日期(Application Date) IPC分类号 CPC分类号 Position Value
14725838 2015-05-29 A23B 5/04, A23B 5/045 A23B 5/04, A23B 5/45, A23L 15/20 F I
14814205 2015-07-30 A61H 33/00, C01B 33/107, E04B 1/84 A61H 33/6063, A61H 33/6042 F I
15189723 2016-06-22 D04B 1/00 B65H2301/44514, C01B 33/1071, F16F 15/2, H01L 27/14641 L A
14711011 2015-05-13 B32B 17/10, B32B 27/32 G06F 3/485 L A
14515267 2014-10-15 F16F 15/02, G09G 5/34, G06F 3/0485 A01B 15/06, A01B 15/06 L I

【参考答案】

Classification.java
package cn.edu.bjut.chapter5;
 
public class Classification {
	protected char section;
	protected int mainClass;
	protected char subclass;
	protected int mainGroup;
	protected int subgroup;
 
	public final static char SEPARATOR = '/';
 
	public Classification(char section, int mainClass, char subclass, int mainGroup, int subgroup) {
		this.section = section;
		this.mainClass = mainClass;
		this.subclass = subclass;
		this.mainGroup = mainGroup;
		this.subgroup = subgroup;
	}
 
	// example: G09F 17/30
	public Classification(String symbol) {
		this.section = symbol.charAt(0);
		this.mainClass = Integer.parseInt(symbol.substring(1, 3));
		this.subclass = symbol.charAt(3);
 
		int pos = symbol.indexOf(SEPARATOR);
		this.mainGroup = Integer.parseInt(symbol.substring(4, pos).trim());
		this.subgroup = Integer.parseInt(symbol.substring(pos + 1));
	}
 
	public char getSection() {
		return section;
	}
 
	public void setSection(char section) {
		this.section = section;
	}
 
	public int getMainClass() {
		return mainClass;
	}
 
	public void setMainClass(int mainClass) {
		this.mainClass = mainClass;
	}
 
	public char getSubclass() {
		return subclass;
	}
 
	public void setSubclass(char subclass) {
		this.subclass = subclass;
	}
 
	public int getMainGroup() {
		return mainGroup;
	}
 
	public void setMainGroup(int mainGroup) {
		this.mainGroup = mainGroup;
	}
 
	public int getSubgroup() {
		return subgroup;
	}
 
	public void setSubgroup(int subgroup) {
		this.subgroup = subgroup;
	}
 
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
 
		sb.append(section);
 
		sb.append(String.format("%2s", mainClass).replace(' ', '0'));
 
		sb.append(subclass);
 
		sb.append(String.format("%4s", mainGroup));
 
		sb.append(SEPARATOR);
 
		sb.append(subgroup);
 
		return sb.toString();
	}
}
Ipc.java
package cn.edu.bjut.chapter5;
 
public class Ipc extends Classification {
 
	public Ipc(char section, int mainClass, char subclass, int mainGroup, int subgroup) {
		super(section, mainClass, subclass, mainGroup, subgroup); 
	}
 
	public Ipc(String symbol) {
		super(symbol); 
	}
 
	public static void main(String[] args) {
		char section = 'A'; 
		int mainClass = 4; 
		char subclass = 'B'; 
		int mainGroup = 55; 
		int subgroup = 56; 
 
		Classification ipc = new Ipc(section, mainClass, subclass, mainGroup, subgroup); 
		System.out.println(ipc); 
 
		String symbol = "G09F 17/30"; 
		System.out.println(new Ipc(symbol)); 
	}
}
Cpc.java
package cn.edu.bjut.chapter5;
 
public class Cpc extends Classification {
	private char position; 
	private char value; 
 
	public Cpc(char section, int mainClass, char subclass, int mainGroup, int subgroup, char position, char value) {
		super(section, mainClass, subclass, mainGroup, subgroup); 
 
		this.position = position; 
		this.value = value; 
	}
 
	public Cpc(String symbol, char position, char value) {
		super(symbol); 
 
		this.position = position; 
		this.value = value; 
	}
 
	public char getPosition() {
		return position;
	}
 
	public void setPosition(char position) {
		this.position = position;
	}
 
	public char getValue() {
		return value;
	}
 
	public void setValue(char value) {
		this.value = value;
	}
}
Date.java
package cn.edu.bjut.chapter5;
 
public class Date {
	private int year, month, day;
 
	public Date(int year, int month, int day) {
		this.year = year;
		this.month = month;
		this.day = day;
	}
 
	// format: YYYY-MM-DD
	public Date(String str) {
		String[] parts = str.trim().split("-"); 
		this.year = Integer.parseInt(parts[0]); 
		this.month = Integer.parseInt(parts[1]); 
		this.day = Integer.parseInt(parts[2]); 
	}
 
	public int getYear() {
		return year;
	}
 
	public void setYear(int year) {
		this.year = year;
	}
 
	public int getMonth() {
		return month;
	}
 
	public void setMonth(int month) {
		this.month = month;
	}
 
	public int getDay() {
		return day;
	}
 
	public void setDay(int day) {
		this.day = day;
	}
 
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
 
		sb.append(year);
		if (month < 10) {
			sb.append("0" + month);
		} else {
			sb.append(month);
		}
		if (day < 10) {
			sb.append("0" + day);
		} else {
			sb.append(day);
		}
 
		return sb.toString();
	}
}
Patent.java
package cn.edu.bjut.chapter5;
 
public class Patent {
	private String applicationNo; 
	private Date applicationDate; 
	private Ipc[] ipcs; 
	private Cpc[] cpcs; 
 
	private final static String SEPERATOR = ","; 
 
	public Patent(String applicationNo, Date applicationDate, Ipc[] ipcs, Cpc[] cpcs) {
		this.applicationNo = applicationNo; 
		this.applicationDate = applicationDate; 
		this.ipcs = ipcs; 
		this.cpcs = cpcs; 
	}
 
	public Patent(String applicationNo, String applicationDate, String multiIpcs, String multiCpcs, char position, char value) {
		this.applicationNo = applicationNo; 
		this.applicationDate = new Date(applicationDate); 
 
		String[] ipcSymbols = multiIpcs.split(SEPERATOR); 
		this.ipcs = new Ipc[ipcSymbols.length]; 
		for (int i = 0; i < ipcSymbols.length; i++) {
			ipcs[i] = new Ipc(ipcSymbols[i].trim()); 
		}
 
		String[] cpcSymbols = multiCpcs.split(SEPERATOR); 
		this.cpcs = new Cpc[cpcSymbols.length]; 
		for (int i = 0; i < cpcSymbols.length; i++) {
			cpcs[i] = new Cpc(cpcSymbols[i].trim(), position, value); 
		}
	}
 
	public String getApplicationNo() {
		return applicationNo;
	}
 
	public void setApplicationNo(String applicationNo) {
		this.applicationNo = applicationNo;
	}
 
	public Date getApplicationDate() {
		return applicationDate;
	}
 
	public void setApplicationDate(Date applicationDate) {
		this.applicationDate = applicationDate;
	}
 
	public Ipc[] getIpcs() {
		return ipcs;
	}
 
	public void setIpcs(Ipc[] ipcs) {
		this.ipcs = ipcs;
	}
 
	public Cpc[] getCpcs() {
		return cpcs;
	}
 
	public void setCpcs(Cpc[] cpcs) {
		this.cpcs = cpcs;
	}
 
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder(); 
 
		sb.append(applicationNo + "\t" + applicationDate + "\t"); 
 
		sb.append("["); 
		for (int i = 0; i < ipcs.length - 1; i++) {
			sb.append(ipcs[i] + SEPERATOR); 
		}
		sb.append(ipcs[ipcs.length - 1] + "]\t"); 
 
		sb.append("["); 
		for (int i = 0; i < cpcs.length - 1; i++) {
			sb.append(cpcs[i] + SEPERATOR); 
		}
		sb.append(cpcs[cpcs.length - 1] + "]"); 
 
		return sb.toString(); 
	}
 
	public static void main(String[] args) {
		Patent[] patents = new Patent[5]; 
		patents[0] = new Patent("14725838", "2015-05-29", "A23B 5/04, A23B 5/045", "A23B 5/04, A23B 5/45, A23L 15/20", 'F', 'I'); 
		patents[1] = new Patent("14814205", "2015-07-30", "A61H 33/00, C01B 33/107, E04B 1/84", "A61H 33/6063, A61H 33/6042", 'F', 'I'); 
		patents[2] = new Patent("15189723", "2016-06-22", "D04B 1/00", "B65H2301/44514, C01B 33/1071, F16F 15/2, H01L 27/14641", 'L', 'A'); 
		patents[3] = new Patent("14711011", "2015-05-13", "B32B 17/10, B32B 27/32", "G06F 3/485", 'L', 'A'); 
		patents[4] = new Patent("14515267", "2014-10-15", "F16F 15/02, G09G 5/34, G06F 3/0485", "A01B 15/06, A01B 15/06", 'L', 'I'); 
 
		for (Patent patent: patents) {
			System.out.println(patent); 
		}
	}
}

返回Java课程页

zh/courses/java2025/ch05.1743341582.txt.gz · 最后更改: 2025/03/30 21:33 由 pzczxs