二、程序设计题(15分)。
For the following five Fibonacci numbers :13,21,34,55,89. Try to write a method , the parameter is a positive integer , the return type is String . In the returned string , show whether the actual parameter is a member of the above Fibonacci numbers or its multiple .( Tips : Just write the method , not the complete program .)
程序设计题(15分)。以下五个斐波那契数: 13,21,34,55,89。尝试写一个方法,参数是一个正整数,返回类型是 String。在返回的字符串中,显示实际参数是上述斐波那契数字的成员还是它的倍数。(提示: 只写方法,不要写完整的程序。)
public String fibonacciOrMultiple(int n) {
if (n == 0) {
return "fibonacci";
}
int[] fibonacci = {13, 21, 34, 55, 89};
for (int i = 0; i < fibonacci.length; i++) {
if (n == fibonacci[i]) {
return "fibonacci";
} else if (n % fibonacci[i] == 0) {
return "multiple of fibonacci";
}
}
return "neither fibonacci nor multiple";
}
三、程序设计题(15分)。
For following class Student :
public class Student {
public String no ;// student ID
public String name ;// student name
public char gender ;// student gender
The requirements are as follows :
(1) Override hashCode() and equals () methods of this class .(2) If and only if the student ID and name are the same , the equals () method returns true .(3) Need to avoid the exception that may be generated when the actual parameter is null value .
要求如下: (1)重写这个类的 hashCode ()和 equals ()方法。(2)当且仅当学生 ID 和名称相同时,equals ()方法返回 true。(3)需要避免当实际参数为空值时可能产生的异常。
public class Student {
public String no; // student ID
public String name; // student name
public char gender;// student gender
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((no == null) ? 0 : no.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (no == null) {
if (other.no != null)
return false;
} else if (!no.equals(other.no))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
在`hashCode`方法中,`prime`是一个质数,这意味着它只能被1和它本身整除。在实现hashcode时通常会选择一个恰当的大质数值(通常是31),因为这取决于具体语言的实现细节。将一个对象转换为哈希码时,需要用其各个成员变量的哈希码乘以一个大质数并相加,最终得到一个哈希值。这就是 `hashCode` 方法的常规实现方式,而经验表明31是一个不错的选择,因为它几乎可以保证不发生哈希冲突。在 Java 平台中许多库类都使用 31 作为乘数来计算 hash 值(例如String类)。
在Java中,每个对象都有一个`hashCode()`方法。 `hashCode()`是返回int类型的哈希码值,用于散列表数据结构高效存储和快速查找对象。HashCode是一种高效的哈希算法,它能够将任意大小的数据映射到一个固定大小的数据集上(经常是一个较小的整数),并且将散列结果分布在整个散列空间中。当需要搜索大量的项时,哈希表可提供一个相对恒定的时间进行搜索,因此是常用数据结构之一。为了保证hash表等数据结构能够正常工作,两个具有相同语义的对象必须具有相同的哈希码值,否则这些对象会被散列到不同的哈希桶里面,从而导致无法正确访问某些元素。重写`equals()`方法,则还需要重写`hashCode()`方法,以保证相等的对象具有相等的哈希码值。只有这样,才能保证该对象可以在哈希表中正常使用。
equals()遵循以下规则来判断两个 Student
对象是否相等
- 如果两个引用指向同一个对象,则认为它们相等,直接返回 true。
- 如果传递进的参数为空,则返回 false。
- 如果传递进来的参数类型与当前对象的类型不同,则返回 false。
- 将传递进来对象强制转换成
Student
类型,并将其赋值给other
。 - 判断当前对象的
no
和name
是否为空,如果为空,则判断传递进来的对象对应的成员也是否为空,为空则认为不相等,反之则相等。 - 如果当前对象的
no
和name
不为空,则使用equals()
方法比较当前对象和传递进来的对象的每个成员变量状态是否相等,如果相等返回true,否则返回false.
四、程序设计题(15分)。
Write a wrapper class for the basic character input stream , which adds a line number and a colon “:” in front of each line text while reading a file .
为基本字符输入流编写一个包装类,它在读取文件时在每行文本前添加一个行号和冒号“:”。
可以使用Java中的装饰器模式(Decorator Pattern)来为基本字符输入流添加指定的功能,如在每行文本前添加一个行号和冒号。有了装饰器模式,我们可以将一个类包装成另一个更强大的类,而不需要对原始类做出任何改变。
下面是一个使用装饰器模式编写的基本字符输入流包装器,实现读取文件时在每行文本前添加行号和冒号的功能:
import java.io.*;
public class NumberedLineReader extends BufferedReader {
private int lineNumber = 1;
public NumberedLineReader(Reader in) {
super(in);
}
@Override
public String readLine() throws IOException {
String line = super.readLine();
if (line != null) {
line = lineNumber++ + ": " + line;
}
return line;
}
}
这个 `NumberedLineReader` 类继承自 `BufferedReader`,并在其基础上重写了 `readLine()` 方法。在读取文件时,先通过 `super.readLine()` 方法获取到一行文本,然后将行号加上去,并返回该行文本。这样,使用 `NumberedLineReader` 实例读取文件时,每行文本都会带着行号和冒号,同时也能保留原来 `BufferedReader` 的所有功能。
使用方法示例如下:
try (FileReader fileReader = new FileReader("foo.txt");
BufferedReader reader = new NumberedLineReader(fileReader)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
注:以上示例只是演示了使用方式,具体需要根据实际文件路径和文件名来读取对应文件。
五、程序设计题(15分)。
In the well - nown storyof " The tortoise and the hare ", the hare was too confident and took a break in the middle of the competition , which led to the tortoise winning the competition . A multi - threaded program is required to simulate the race between the tortoise and the hare . The speed of the tortoise is 1 meter per 1500 milliseconds , and the speed of the hare is 5 meters per 500 milliseconds . When the hare reached the 700th meter , it chose to rest for 10,000 milliseconds . As a result , the tortoise wins the race . The output result of the program running is shown in the figure .
在著名的“龟兔赛跑”故事中,兔子太过自信,在比赛中途休息,结果乌龟赢得了比赛。需要一个多线程程序来模拟龟兔赛跑之间的竞赛。乌龟的速度是每1500毫秒1米,兔子的速度是每500毫秒5米。当野兔跑到第700米时,它选择休息10,000毫秒。结果,乌龟赢得了比赛。程序运行的输出结果如图所示。
public class Race {
private static boolean finished = false;
public static void main(String[] args) {
Thread tortoise = new Thread(new Tortoise());
Thread hare = new Thread(new Hare());
System.out.println("Get ready...");
try {
Thread.sleep(1000); // 等待1秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Go!");
tortoise.start();
hare.start();
while (!finished) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Tortoise implements Runnable {
private int position;
private final int distance = 1000; // 比赛总路程
@Override
public void run() {
while (position < distance && !finished) {
try {
Thread.sleep(1500); // 乌龟每1500ms移动1米
} catch (InterruptedException e) {
e.printStackTrace();
}
position++;
System.out.println("Tortoise: " + position + " meters");
}
finish(this.getClass().getSimpleName());
}
}
static class Hare implements Runnable {
private int position;
private final int distance = 1000; // 比赛总路程
@Override
public void run() {
while (position < distance && !finished) {
if (position >= 700) {
try {
Thread.sleep(10000); // 兔子在700米时休息10秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.sleep(500); // 兔子每500ms移动5米
} catch (InterruptedException e) {
e.printStackTrace();
}
position += 5;
System.out.println("Hare: " + position + " meters");
}
}
if (!finished) {
finish(this.getClass().getSimpleName());
}
}
}
private static void finish(String winner) {
finished = true;
System.out.println(winner + " wins!");
}
}