用户工具

站点工具


zh:courses:java2025:ch02

这是本文档旧的修订版!


第二章:Java语言基础

课件

下载:Java语言基础

整型数据测试程序

IntegerTester.java
package cn.edu.bjut.chapter2;
 
public class IntegerTester {
	public static void main(String[] args) {
		System.out.println(Short.MIN_VALUE);
		System.out.println(Short.MAX_VALUE);
		System.out.println(Byte.MIN_VALUE);
		System.out.println(Byte.MAX_VALUE);
 
		byte a = 5;
		String a2 = String.format("%8s", Integer.toBinaryString(a & 0xFF)).replace(' ', '0');
		System.out.println(a2);
		System.out.format("0x%x\n", a);
		System.out.format("0%o\n", a);
 
		byte b = -5;
		String b2 = String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
		System.out.println(b2);
		System.out.format("0x%x\n", b);
		System.out.format("0%o\n", b);
	}
}

字符型数据测试程序

CharTester.java
package cn.edu.bjut.chapter2;
 
public class CharTester {
	public static void main(String[] args) {
		char zhchar = '中';
		char enchar = 'a';
		char enchar2 = 97;
 
		System.out.println(zhchar + "\t" + enchar + "\t" + enchar2);
 
		char ucchar = '\u0061';
		System.out.println(ucchar);
 
		char occhar = '\101';
		System.out.println(occhar);
	}
}

浮点型数据测试程序

DoubleTester.java
package cn.edu.bjut.chapter2;
 
public class DoubleTester {
	public static void main(String[] args) {
		double d = 0.0 / 0.0;
		System.out.println(d);
 
		double a = 2.0;
		double b = 1.91;
		double c = 0.09;
		System.out.println(a - b == c);
		System.out.println(a - b);
		System.out.println(Math.abs(a - b - c) < 1E-6);
	}
}

常量变量示例程序

ConstVariable.java
package cn.edu.bjut.chapter2;
 
public class ConstVariable {
	public static void main(String args[]) {
		boolean x, y, z;
		int a = 89, b = 20;
		x = (a > b);
		y = (a != b);
		z = (a + b == 43);
		System.out.println("x=" + x);
		System.out.println("y=" + y);
		System.out.println("z=" + z);
 
		final String BJUT = "Beijing University of Technology";
		System.out.println(BJUT);
 
		final int UPPER_LIMIT = 1, LOWER_LIMIT = 0;
		System.out.println("[" + LOWER_LIMIT + ", " + UPPER_LIMIT + "]");
	}
}

程序控制流:if

java.util.Random类的方法nextInt()产生随机整数,生成两个随机整数,用if-else 语句找出较小者

IfElse.java
package cn.edu.bjut.chapter2;
 
import java.util.Random;
 
public class IfElse {
	public static void main(String[] args) {
		Random random = new Random(); // 声明随机数类对象并实例化
		int m = random.nextInt(); // 产生随机整数
		System.out.println("m = " + m);
		int n = random.nextInt(); // 产生下一个随机整数
		System.out.println("n = " + n);
		if (m < n) {
			System.out.println("The minimum of m and n is " + m);
		} else if (n < m) {
			System.out.println("The minimum of m and n is " + n);
		} else {
			System.out.println("m is equal to n");
		}
	}
}

程序控制流:switch

产生从1 到12 的随机整数month,根据month 的值显示相应的月份

SwitchExample.java
package cn.edu.bjut.chapter2;
 
import java.util.Random;
 
public class SwitchExample {
	public static void main(String[] args) {
		Random random = new Random(); // 声明随机数类对象并实例化
		float x = random.nextFloat(); // 产生0.0 到1.0 的随机浮点数
		int month = Math.round(11 * x + 1); // 产生1 到12 的随机整数
		switch (month) {
		case 1:
			System.out.println("1月");
			break;
		case 2:
			System.out.println("2月");
			break;
		case 3:
			System.out.println("3月");
			break;
		case 4:
			System.out.println("4月");
			break;
		case 5:
			System.out.println("5月");
			break;
		case 6:
			System.out.println("6月");
			break;
		case 7:
			System.out.println("7月");
			break;
		case 8:
			System.out.println("8月");
			break;
		case 9:
			System.out.println("9月");
			break;
		case 10:
			System.out.println("10月");
			break;
		case 11:
			System.out.println("11月");
			break;
		case 12:
			System.out.println("12月");
			break;
		default:
			System.out.println("错误");
		}
	}
}

程序控制流:while与do-while

编写一个程序,使用while 语句复制一个给定字符串的各个字符,直到程序找到给定字符u 为止。

WhileExample.java
package cn.edu.bjut.chapter2;
 
public class WhileExample {
	public static void main(String[] args) {
		String copyFromMe = "Copy every letter until you encounter 'u'."; // 给定字符串
		StringBuffer copyToMe = new StringBuffer(); // 创建一个空的串变量
		int i = 0;
		char c = copyFromMe.charAt(i); // 该串变量的第一个字符赋给c
		while (c != 'u') {
			copyToMe.append(c);
			c = copyFromMe.charAt(++i);
		}
		System.out.println(copyToMe);
	}
}

程序控制流:for

求解Fibonacci数列1, 1, 2, 3, 5, 8, …的前36个数。该数列的递推关系是: \begin{eqnarray} \nonumber \begin{cases} F_1 = 1, & n = 1 \\ F_2 = 1, & n = 2 \\ F_n = F_{n - 1} + F_{n - 2}, & n \ge 3 \end{cases} \end{eqnarray}

Fibonacci.java
package cn.edu.bjut.chapter2;
 
public class Fibonacci {
	public static void main(String[] args) {
		int f1 = 1, f2 = 1;
		for (int i = 1; i < 38 / 2; i++) {
			System.out.println("\t" + f1 + "\t" + f2);
			f1 += f2;
			f2 += f1;
		}
	}
}

编写一个程序,使用for语句复制一个给定字符串的各个字符,直到程序找到给定字符u 为止。

ForExample.java
package cn.edu.bjut.chapter2;
 
public class ForExample {
	public static void main(String[] args) {
		String copyFromMe = "Copy every letter until you encounter 'u'."; // 给定字符串
		StringBuffer copyToMe = new StringBuffer();// 创建一个空的串变量
		int i;
		char c;
 
		for (i = 0, c = copyFromMe.charAt(i); i < copyFromMe.length() && c != 'u'; 
				c = copyFromMe.charAt(++i)) {
			copyToMe.append(c);
		}
		System.out.println(copyToMe);
	}
}

程序控制流:break

求自然数1至50间的素数

PrimeNumber.java
package cn.edu.bjut.chapter2;
 
public class PrimeNumber {
	public static void main(String[] args) {
		int n = 0, m, j, i;
		System.out.print("2");
		label: for (i = 3; i <= 100; i += 2) {
			m = (int) Math.sqrt((double) i);
			for (j = 2; j <= m; j++) {
				if ((i % j) == 0) {
					break;
				}
				if (i == 51) {
					break label;
				}
			}
			if (j >= m + 1) {
				if (n % 6 == 0) {
					System.out.println("\n");
				}
				System.out.print(i + "  ");
				n++;
			}
		}
	}
}

程序控制流:contine

ContinueExample.java
package cn.edu.bjut.chapter2;
 
public class ContinueExample {
	public static void main(String[] args) {
		label: for (int i = 0; i < 2; i++) {
			System.out.println("运行第一重循环" + i);
			for (int j = 0; j < 2; j++) {
				System.out.println("运行第二重循环" + j);
 
				for (int k = 0; k < 2; k++) {
					// continue label;
					if (k == 1) {
						System.out.println("跳出多重循环");
						continue label;
					}
 
					System.out.println("运行第三重循环" + k);
					System.out.println("**************************");
				}
			}
		}
	}
}

上机作业

  • 编写程序,求$1 + 3 + 7 + 15 + 31 + \cdots + (2^{20} - 1)$的值;

【参考答案】

TowPowSummation.java
package cn.edu.bjut.chapter2;
 
public class TwoPowerSummation {
	public static void main(String[] args) {
		int sum = 0; 
		for (int n = 1; n <= 20; n++) {
			sum += (int) Math.pow(2, n) - 1; 
		}
 
		System.out.println(sum);
	}
}
  • 已知$S = 1 - \frac{1}{2} + \frac{1}{3} - \frac{1}{4} + \cdots + \frac{1}{n - 1} - \frac{1}{n}$,试编写程序求解直到满足$\frac{1}{n} < {10}^{-5}$时的$S$值;

【参考答案】

FractionSummation.java
package cn.edu.bjut.chapter2;
 
public class FractionSummation {
	public static void main(String[] args) {
		double sum = 0; 
		for (int n = 1; (1.0 / n >= 1e-5); n++) {
			if (n % 2 == 0) { // 偶数
				sum -= 1.0 / n; 
			} else { // 奇数
				sum += 1.0 / n; 
			}
		}
		System.out.println(sum);
	}
}
  • 编写程序,计算没有数码9的三位数有多少个,它们的和等于多少?

【参考答案】

ThreeDigitNumber.java
package cn.edu.bjut.chapter2;
 
public class ThreeDigitNumber {
	public static void main(String[] args) {
		int count = 0; 
		int sum = 0; 
 
		for (int i = 100; i < 1000; i++) {
			String str = String.valueOf(i); 
			if (str.indexOf('9') >= 0) {
				continue; 
			}
 
			count++; 
			sum += i; 
		}
 
		System.out.println(count + "\t" + sum); 
	}
}
  • 国际专利分类号(IPC)的前15位由section(部),class(大类),subclass(小类),main group(大组)和sub group(小组)五部分组成,每位的要求如下表所示,具体例子如:“G06F 17/30”和“H01M 10/587”,编写程序将这五部分拼接成IPC的实际表现形式;
位数 内容 取值
1 section A..H
2,3 class 1…99
4 subclass A..Z
5-8 main group(右对齐) 1…9999
9 分割符 /
10-14 subgroup(左对齐) 0…99999

【参考答案】

Ipc.java
package cn.edu.bjut.chapter2;
 
public class Ipc {
	public static void main(String[] args) {
		final char SEPARATOR = '/';
 
		{
			char section = 'A';
			int mainClass = 4;
			char subclass = 'B';
			int mainGroup = 55;
			int subgroup = 56;
 
			String classification = section 
                                        + String.format("%2s", mainClass).replace(' ', '0') 
                                        + subclass + String.format("%4s", mainGroup) 
                                        + SEPARATOR + subgroup;
 
			System.out.println(classification);
		}
 
		{
			String classification = "A04B  55/56"; 
			char section = classification.charAt(0); 
			int mainClass = Integer.parseInt(classification.substring(1, 3)); 
			char subclass = classification.charAt(3); 
			int pos = classification.indexOf(SEPARATOR); 
			int mainGroup = Integer.parseInt(classification.substring(4, pos).trim()); 
			int subgroup = Integer.parseInt(classification.substring(pos + 1)); 
 
			System.out.println(section + "\t" + mainClass + "\t" 
                                        + subclass + "\t" + mainGroup + "\t" 
                                        + subgroup); 
		}
	}
}

返回Java课程页

zh/courses/java2025/ch02.1740880176.txt.gz · 最后更改: 2025/03/02 09:49 由 pzczxs