1.编写一个程序,从文本文件读取单词,并按字母的升序显示所有的单词(可以重复)。单词必须以字母开头。文本文件作为命令行参数传递。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: WordSorter <file_path>");
return;
}
String[] words = readFile(args[0]);
Arrays.sort(words);
for (String word : words)
System.out.println(word);
}
private static String[] readFile(String path) {
String[] words = null;
try {
words = new String(Files.readAllBytes(Paths.get(path))).split("\\W+");
for (String word : words)
word = word.trim();
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return words;
}
}
2.编写一个程序,让用户在图形用户界面中输入数字,然后在文本域显示它们,如图所示。使用链表存储这些数字,但不要存储重复的数值。添加按钮Sort、Shuffle和Reverse,分别对该表进行排序、打乱顺序与逆序排列操作。
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringJoiner;
public class MyJavaFx extends Application {
private final ArrayList<Integer> list = new ArrayList<>();
private final TextArea ta = new TextArea();
@Override
public void start(Stage stage) {
// 设置界面
VBox vBox = new VBox(5);
HBox hBox = new HBox(15);
TextField tf = new TextField();
hBox.getChildren().addAll(new Label("请输入数字: "), tf);
hBox.setAlignment(Pos.CENTER);
ta.setEditable(false);
Button btSort = new Button("Sort");
Button btShuffle = new Button("Shuffle");
Button btReverse = new Button("Reverse");
HBox btBox = new HBox(25);
btBox.getChildren().addAll(btSort, btShuffle, btReverse);
btBox.setAlignment(Pos.CENTER);
vBox.getChildren().addAll(hBox, ta, btBox);
// 输入数字
tf.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode() == KeyCode.ENTER) {
String s = tf.getText();
try {
int x = Integer.parseInt(s);
list.add(x);
ta.setText(ta.getText() + ' ' + s);
tf.setText("");
} catch (NumberFormatException e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setHeaderText("输入格式错误");
alert.setContentText("输入的不是整数!\n请重新输入!");
alert.show();
}
}
});
btSort.setOnAction(actionEvent -> {
Collections.sort(list);
refreshText();
});
btShuffle.setOnAction(actionEvent -> {
Collections.shuffle(list);
refreshText();
});
btReverse.setOnAction(actionEvent -> {
Collections.reverse(list);
refreshText();
});
// 设置舞台
stage.setTitle("Exercise20_02");
stage.setScene(new Scene(vBox));
stage.show();
}
// 将列表中的值显示到文本区域中
private void refreshText() {
StringJoiner joiner = new StringJoiner(" ");
for (int x : list)
joiner.add(String.valueOf(x));
ta.setText(joiner.toString());
}
public static void main(String[] args) {
Application.launch(args);
}
}
3.改写编程练习题8.37,保存州和首府的匹配对,从而随机显示问题。
import java.util.Random;
import java.util.Scanner;
public class Test {
public static final String[][] province = {{"河北", "石家庄"}, {"山西", "太原"}, {"辽宁", "沈阳"}, {"吉林", "长春"}, {"黑龙江", "哈尔滨"}, {"江苏", "南京"}, {"浙江", "杭州"}, {"安徽", "合肥"}, {"福建", "福州"}, {"江西", "南昌"}, {"山东", "济南"}, {"河南", "郑州"}, {"湖北", "武汉"}, {"湖南", "长沙"}, {"广东", "广州"}, {"海南", "海口"}, {"四川", "成都"}, {"贵州", "贵阳"}, {"云南", "昆明"}, {"陕西", "西安"}, {"甘肃", "兰州"}, {"青海", "西宁"}, {"台湾", "台北"}, {"内蒙古", "呼和浩特"}, {"广西", "南宁"}, {"西藏", "拉萨"}, {"宁夏", "银川"}, {"新疆", "乌鲁木齐"}};
public static void main(String[] args) {
Random random = new Random(System.currentTimeMillis());
Scanner scanner = new Scanner(System.in);
for (; ; ) {
int i = random.nextInt(28);
System.out.println("哪个城市是" + province[i][0] + "的省会?");
String s = scanner.next();
System.out.println(s.equals(province[i][1]) ? "恭喜你,回答正确!" : province[i][0] + "的省会是" + province[i][1] + '。');
}
}
}
4.编写一个程序,满足下面的要求:使用Point2D
随机创建100个点,并且应用Arrays.sort(list, Comparator)
方法进行排序,首先通过
y
y
y坐标的升序对点进行排序,如果
y
y
y相同,则按照
x
x
x坐标的升序排序。显示前5个点的
x
x
x和
y
y
y坐标。
import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;
public class Test {
public static void main(String[] args) {
Point2D[] points = new Point2D.Double[100];
Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < 100; i++)
points[i] = new Point2D.Double(random.nextDouble(), random.nextDouble());
Arrays.sort(points, new Comparator<Point2D>() {
@Override
public int compare(Point2D o1, Point2D o2) {
if (o1.getY() > o2.getY()) return 1;
if (o1.getY() == o2.getY())
if (o1.getX() > o2.getX())
return 1;
else if (o1.getX() == o2.getX())
return 0;
return -1;
}
});
for (int i = 0; i < 5; i++)
System.out.printf("(%f,%f)\n", points[i].getX(), points[i].getY());
}
}
6.编写一个测试程序,在一个链表上存储500万个整数,测试分别使用iterator
和get(index)
方法的遍历时间。
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Test {
private static final List<Integer> list = new LinkedList<>();
public static void main(String[] args) {
for (int i = 0; i < 5000000; i++)
list.add(i);
long startTime, endTime;
startTime = System.currentTimeMillis();
indexTravers();
endTime = System.currentTimeMillis();
System.out.println("下标法遍历耗时:" + (endTime - startTime) + "纳秒。");
startTime = System.currentTimeMillis();
iteratorTravers();
endTime = System.currentTimeMillis();
System.out.println("迭代器法遍历耗时:" + (endTime - startTime) + "纳秒。");
}
private static void indexTravers() {
for (int i = 0; i < list.size(); i++)
list.get(i);
}
private static void iteratorTravers() {
Iterator<Integer> it = list.iterator();
while (it.hasNext())
it.next();
}
}
10.编写一个程序创建两个优先队列{"George", "Jim", "John", "Blake", "Kevin", "Michael"}
和{"George", "Katie", "Kevin", "Michelle", "Ryan"}
,求它们的并集、差集和交集。
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
public class Test {
public static void main(String[] args) {
PriorityQueue<String> queue1 = new PriorityQueue<>();
queue1.addAll(List.of("George", "Jim", "John", "Blake", "Kevin", "Michael"));
PriorityQueue<String> queue2 = new PriorityQueue<>();
queue2.addAll(List.of("George", "Katie", "Kevin", "Michelle", "Ryan"));
HashSet<String> set1 = new HashSet<>(queue1);
HashSet<String> set2 = new HashSet<>(queue2);
// 计算并集
HashSet<String> union = new HashSet<>(set1);
union.addAll(set2);
// 计算差集
HashSet<String> difference = new HashSet<>(set1);
difference.removeAll(set2);
// 计算交集
HashSet<String> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
// 打印结果
System.out.println("Union: " + union);
System.out.println("Difference (set1 - set2): " + difference);
System.out.println("Intersection: " + intersection);
}
}
11.Java程序包含各种编组符号对,例如:
- 圆括号:
(
和)
- 方括号:
[
和]
- 花括号:
{
和}
请注意编组符号不能交叉。例如,(a{b)}
是不合法的。编写一个程序,检查一个Java源程序中的编组符号是否都正确匹配了。将源代码文件的名字作为命令行参数传递。
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
public class Test {
private static final byte ROUND_BRACKET = 0;
private static final byte SQUARE_BRACKET = 1;
private static final byte CURLY_BRACKET = 2;
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("命令行参数有误!");
return;
}
try (FileReader fileReader = new FileReader(args[0])) {
int c;
Stack<Byte> stack = new Stack<>();
while ((c = fileReader.read()) != -1)
switch ((char) c) {
case '(':
stack.push(ROUND_BRACKET);
break;
case '[':
stack.push(SQUARE_BRACKET);
break;
case '{':
stack.push(CURLY_BRACKET);
break;
case ')':
if (stack.isEmpty() || stack.pop() != ROUND_BRACKET) {
fileReader.close();
System.out.println("括号不匹配!");
return;
}
break;
case ']':
if (stack.isEmpty() || stack.pop() != SQUARE_BRACKET) {
fileReader.close();
System.out.println("括号不匹配!");
return;
}
break;
case '}':
if (stack.isEmpty() || stack.pop() != CURLY_BRACKET) {
fileReader.close();
System.out.println("括号不匹配!");
return;
}
}
if (stack.isEmpty())
System.out.println("括号成功匹配!");
else
System.out.println("括号不匹配!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
12.定义MyPriorityQueue
类,继承自PriorityQueue
并实现Cloneable
接口和clone()
方法,以克隆一个优先队列。
import java.util.PriorityQueue;
public class MyPriorityQueue<E> extends PriorityQueue<E> implements Cloneable {
public MyPriorityQueue() {
}
public MyPriorityQueue(int initialCapacity) {
super(initialCapacity);
}
@Override
public MyPriorityQueue<E> clone() {
MyPriorityQueue<E> es = new MyPriorityQueue<>(super.size());
es.addAll(this);
return es;
}
}
17.编写一个程序,检查是否有4个给定数的24点解决方案。该程序让用户输入在1到13之间的4个值,如图所示,。然后用户可以单击Solve按钮显示解决方案,若不存在解决方案,则提示“不存在解决方案”。
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class MyJavaFx extends Application {
private static final char[] operator = {'+', '-', '*', '/'};
@Override
public void start(Stage stage) {
VBox vBox = new VBox();
HBox hBox = new HBox();
TextField resTf = new TextField();
resTf.setEditable(false);
Button button = new Button("Solve");
hBox.getChildren().addAll(resTf, button);
hBox.setAlignment(Pos.CENTER);
TextField tf1 = new TextField();
tf1.setFont(new Font(20));
tf1.setAlignment(Pos.CENTER);
tf1.setPrefWidth(70);
TextField tf2 = new TextField();
tf2.setFont(new Font(20));
tf2.setAlignment(Pos.CENTER);
tf2.setPrefWidth(70);
TextField tf3 = new TextField();
tf3.setFont(new Font(20));
tf3.setAlignment(Pos.CENTER);
tf3.setPrefWidth(70);
TextField tf4 = new TextField();
tf4.setFont(new Font(20));
tf4.setAlignment(Pos.CENTER);
tf4.setPrefWidth(70);
HBox numBox = new HBox();
numBox.getChildren().addAll(tf1, tf2, tf3, tf4);
vBox.getChildren().addAll(hBox, numBox);
/*TextFormatter<String> digitInputFormatter = new TextFormatter<String>(new UnaryOperator<TextFormatter.Change>() {
@Override
public TextFormatter.Change apply(TextFormatter.Change change) {
String s = change.getText();
return s.matches("[1-9]")||s.matches("1[0-3]")?change:null;
}
});
tf1.setTextFormatter(digitInputFormatter);
tf2.setTextFormatter(digitInputFormatter);
tf3.setTextFormatter(digitInputFormatter);
tf4.setTextFormatter(digitInputFormatter);*/
tf1.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String s, String t1) {
if (!t1.matches("[1-9]") && !t1.matches("1[0-3]"))
tf1.setText(s);
}
});
tf2.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String s, String t1) {
if (!t1.matches("[1-9]") && !t1.matches("1[0-3]"))
tf2.setText(s);
}
});
tf3.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String s, String t1) {
if (!t1.matches("[1-9]") && !t1.matches("1[0-3]"))
tf3.setText(s);
}
});
tf4.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String s, String t1) {
if (!t1.matches("[1-9]") && !t1.matches("1[0-3]"))
tf4.setText(s);
}
});
button.setOnAction(actionEvent -> {
byte[] a = new byte[4];
a[0] = Byte.parseByte(tf1.getText());
a[1] = Byte.parseByte(tf2.getText());
a[2] = Byte.parseByte(tf3.getText());
a[3] = Byte.parseByte(tf4.getText());
resTf.setText(solve(a));
});
stage.setTitle("Exercise20_17");
stage.setScene(new Scene(vBox));
stage.show();
}
// 求解24点
private static String solve(byte[] num) {
for (short i = 1; i > 0; ++i) {
byte i1 = (byte) (i & 3), i2 = (byte) ((i >> 2) & 3);
if (i1 == i2) continue;
byte i3 = (byte) ((i >> 4) & 3);
if (i1 == i3 || i2 == i3) continue;
byte i4 = (byte) ((i >> 6) & 3);
if (i1 == i4 || i2 == i4 || i3 == i4) continue;
float x1;
byte op1 = (byte) ((i >> 8) & 3);
switch (op1) {
case 0:
x1 = num[i2] + num[i1];
break;
case 1:
x1 = num[i2] - num[i1];
break;
case 2:
x1 = num[i2] * num[i1];
break;
default:
if (num[i1] == 0) continue;
x1 = (float) num[i2] / num[i1];
}
if ((i & 0x4000) == 0) {
byte op2 = (byte) ((i >> 10) & 3);
switch (op2) {
case 0:
x1 += num[i3];
break;
case 1:
x1 = num[i3] - x1;
break;
case 2:
x1 *= num[i3];
break;
default:
if (Math.abs(x1) < 0.01) continue;
x1 = num[i3] / x1;
}
byte op3 = (byte) (i >> 12);
switch (op3) {
case 0:
x1 += num[i4];
break;
case 1:
x1 = num[i4] - x1;
break;
case 2:
x1 *= num[i4];
break;
default:
if (Math.abs(x1) < 0.01) continue;
x1 = num[i4] / x1;
}
if (Math.abs(x1 - 24) < 0.01) {
StringBuilder sb = new StringBuilder(String.valueOf(num[i4]));
sb.append(operator[op3]);
boolean b = op2 == 3 || (op2 == 2 || op2 == 1) && (op1 == 0 || op1 == 1);
if (op3 == 3 || (op3 == 2 || op3 == 1) && (op2 == 0 || op2 == 1)) {
sb.append('(').append(num[i3]).append(operator[op2]);
if (b)
sb.append('(').append(num[i2]).append(operator[op1]).append(num[i1]).append(')');
else
sb.append(num[i2]).append(operator[op1]).append(num[i1]);
sb.append(')');
return sb.toString();
} else {
sb.append(num[i3]).append(operator[op2]);
if (b)
sb.append('(').append(num[i2]).append(operator[op1]).append(num[i1]).append(')');
else
sb.append(num[i2]).append(operator[op1]).append(num[i1]);
return sb.toString();
}
}
} else {
if ((i & 0x2000) != 0) continue;
byte op3 = (byte) ((i >> 10) & 3);
float x2;
switch (op3) {
case 0:
x2 = num[i4] + num[i3];
break;
case 1:
x2 = num[i4] - num[i3];
break;
case 2:
x2 = num[i4] * num[i3];
break;
default:
if (num[i3] == 0) continue;
x2 = (float) num[i4] / num[i3];
}
byte op2 = (byte) ((i >> 12) & 1);
if (op2 == 0)
x1 += x2;
else
x1 -= x2;
if (Math.abs(x1 - 24) < 0.01) {
StringBuilder sb = new StringBuilder(String.valueOf(num[i4]));
sb.append(operator[op3]).append(num[i3]);
if (op2 == 1 && (op1 == 1 || op1 == 0))
sb.append('-').append(num[i2]).append(operator[1 - op1]).append(num[i1]);
else
sb.append(num[i2]).append(operator[op1]).append(num[i1]);
return sb.toString();
}
}
}
return "不存在解决方案!";
}
public static void main(String[] args) {
Application.launch(args);
}
}
18.重写程序清单18-10,不使用递归得到目录的大小。你的程序应该使用队列来存储一个目录下的所有子目录。
public static long getSize(File directory) {
long size = 0;
LinkedList<File> queue = new LinkedList<>();
queue.offer(directory);
while (!queue.isEmpty()) {
File file = queue.poll();
if (file.isFile())
size += file.length();
else {
File[] subFiles = file.listFiles();
if (subFiles != null)
for (File f : subFiles)
queue.offer(f);
}
}
return size;
}