Java课后习题
1.Java入门
1.1阅读程序
1.Person.java。
2.两个字节码,分别是Person.class和Xiti.class。
3.得到“找不到 main 方法”
得到"无法加载主类 xiti"
得到“无法加载主类 xiti.class”
得到“您好,很高兴认识您 nice to meet you”
public class Person {
void speakHello() {
System.out.print("您好,很高兴认识");
System.out.println(" nice to meet you");
}
class Xiti {
public static void main(String[] args) {
Person person = new Person();
person.speakHello();
}
}
}
2.基本数据类型和数组
2.1选择题
- C
- ADF
- B
- BE
- 【代码2】【代码3】【代码4】【代码5】
public static void main(String args[]) {
int x = 8;
byte b = 127; //【代码1】
b = x; //【代码2】
x = 12L; //【代码3】
long y=8.0; //【代码4】
float z=6.89 ; //【代码5】
}
6.B
2.2阅读程序
2.2.1
public class Home {
public static void main (String args[ ]) {
for(int i = 20302; i <= 20322;i++) {
System.out.println((char)i);
}
}
}
/ *
低
住
佐
佑
佒
体
佔
何
佖
佗
佘
余
佚
佛
作
佝
佞
佟
你
佡
佢
Process finished with exit code 0 */
2.2.2
public class Home {
public static void main(String args[]) {
int x = 234,y = 432;
System.out.println(x + "<" + (2 * x));
System.out.print("我输出结果后不回车");
System.out.println("我输出结果后自动回车到下一行");
System.out.println("x+y= " + (x + y));
}
}
//
234<468
我输出结果后不回车我输出结果后自动回车到下一行
x+y= 666
2.2.3
public class Home {
public static void main(String args[]) {
System.out.println("byte取值范围:"+Byte.MIN_VALUE+"至"+Byte.MAX_VALUE);
System.out.println("short取值范围:"+Short.MIN_VALUE+"至"+Short.MAX_VALUE);
System.out.println("int取值范围:"+Integer.MIN_VALUE+"至"+Integer.MAX_VALUE);
System.out.println("long取值范围:"+Long.MIN_VALUE+"至"+Long.MAX_VALUE);
System.out.println("float取值范围:"+Float.MIN_VALUE+"至"+Float.MAX_VALUE);
System.out.println("double取值范围:"+ Double.MIN_VALUE+"至"+Double.MAX_VALUE);
}
}
//
byte取值范围:-128至127
short取值范围:-32768至32767
int取值范围:-2147483648至2147483647
long取值范围:-9223372036854775808至9223372036854775807
float取值范围:1.4E-45至3.4028235E38
double取值范围:4.9E-324至1.7976931348623157E308
2.2.4
public class Home {
public static void main (String args[ ]) {
long[] a = {1, 2, 3, 4};
long[] b = {100, 200, 300, 400, 500};
b = a;
System.out.println("数组b的长度:" + b.length); //【代码1】
System.out.println("b[0]=" + b[0]); //【代码2】
}
}
//
数组b的长度:4
b[0]=1
2.2.5
public class Home {
public static void main (String args[ ]) {
int [] a={10,20,30,40},b[]={{1,2},{4,5,6,7}};
b[0] = a;
b[0][1] = b[1][3];
System.out.println(b[0][3]); //【代码1】
System.out.println(a[1]); //【代码2】
}
}
//
40
7
2.3编程题
public class Home {
public static void main (String args[ ]) {
System.out.println((int)'您');
System.out.println((int)'我');
System.out.println((int)'他');
}
}
//
24744
25105
20182
输出全部的希腊字母:
public class Home {
public static void main (String args[ ]) {
char start='α';
char end='ω';
for(char ch = start; ch <= end; ch++) {
System.out.println(" " + ch);
}
}
}
//
α
β
γ
δ
ε
ζ
η
θ
ι
κ
λ
μ
ν
ξ
ο
π
ρ
ς
σ
τ
υ
φ
χ
ψ
ω
3.运算符、表达式和语句
3.1选择题
- A
- C
- C
3.2阅读程序
**3.2.1 **你,苹,甜
public class Home {
public static void main (String args[]) {
char x = '你', y = 'e', z = '吃';
if(x > 'A'){
y = '苹';
z = '果';
} else {
y = '酸';
}
z = '甜';
System.out.println(x + "," + y + "," + z);
}
}
**3.2.2 **Jeep好好
public class Home {
public static void main (String args[]) {
char c = '\0';
for(int i = 1;i <= 4; i++) {
switch(i) {
case 1: c = 'J';
System.out.print(c);
case 2: c = 'e';
System.out.print(c);
break;
case 3: c = 'p';
System.out.print(c);
default:
System.out.print("好");
}
}
}
}
**3.2.3 **x=-5,y=-1
public class Home {
public static void main (String args[]) {
int x = 1,y = 6;
while (y-- > 0) {
x--;
}
System.out.print("x="+ x +",y=" + y);
}
}
3.3编程题
public class Home {
public static void main (String args[]) {
double sum = 0, a = 1;
int i = 1;
while(i <= 10) {
sum += a;
i++;
a *= i;
}
System.out.println("sum=" + sum);
}
}
// sum=4037913.0
public class Home {
public static void main (String args[]) {
int i,j;
for(j = 2; j <= 100; j++) {
for(i = 2; i <= j /2; i++) {
if(j % i == 0) {
break;
}
}
if(i > j / 2) {
System.out.println(" " + j);
}
}
}
}
public class Home {
public static void main (String args[]) {
double sum = 0, a = 1, i = 1;
do {
sum += a;
i++;
a = 1.0 / (i * a);
} while (i <= 20);
System.out.println("使用do while计算的总和为:" + sum);
for(sum = 0, i = 1,a = 1; i <= 20; i++) {
a = 1.0 / (a * i);
sum += a;
}
System.out.println("使用for循环计算的总和为:" + sum);
}
}
public class Home {
public static void main (String args[]) {
int sum = 0, i,j;
for(i = 1; i <= 1000; i++) {
for(j = 1, sum = 0; j < i; j++) {
if(i % j == 0) {
sum += j;
}
}
if(sum == j) {
System.out.println("完数:" + i);
}
}
}
}
public class Home {
public static void main (String args[]) {
int m = 8, item = m,i = 1;
long sum = 0;
for(i = 1; i <= 10; i++) {
sum += item;
item = item * 10 + m;
}
System.out.println(sum);
}
}
public class Home {
public static void main (String args[]) {
int n = 1;
long sum = 0;
while (true) {
sum += n;
n++;
if(sum >= 8888) {
break;
}
}
System.out.println("符合题意的最大整数为:" + (n - 1));
}
}
// 符合题意的最大整数为:133
4.类与对象
前情知识回顾:
4.1阅读程序
- 1 121 121
- -100
- 27
- 100 20.0
- 将所传参数依次输出
- 最先被执行的静态块
我是静态块
我在了解静态块
4.2编程题
public class CPU {
int speed;
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
}
public class HardDisk {
int amount;
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
public class PC {
HardDisk hd;
CPU cpu;
public void setHardDisk(HardDisk hd) {
this.hd = hd;
}
public void setCPU(CPU cpu) {
this.cpu = cpu;
}
public void show() {
System.out.println("当前cpu的速度为:" + cpu.speed);
System.out.println("当前磁盘容量为:" + hd.amount);
}
}
public class main {
public static void main(String[] args) {
CPU cpu = new CPU();
HardDisk hardDisk = new HardDisk();
PC pc = new PC();
cpu.setSpeed(2200);
hardDisk.setAmount(200);
pc.setCPU(cpu);
pc.setHardDisk(hardDisk);
pc.show(); // 当前cpu的速度为:2200 当前磁盘容量为:200
}
}
5.子类与继承
前情知识回顾:
子类只能有一个父类
上转型对象:
上转型对象调用的一定是子类重写的getM()方法
子类继承的seeM()方法操作的m是被子类隐藏的m
// A.java
public class A {
int m;
int getM() {
return m;
}
int seeM() {
return m;
}
}
//B.java
public class B extends A {
int m;
int getM() {
return m + 100;
}
}
// main.java
public class main {
public static void main(String[] args) {
B b = new B();
b.m = 20;
System.out.println(b.getM()); // 120
A a = b;
a.m = -100; // 上转型对象访问的隐藏的m,即A类中的m
System.out.println(a.getM()); // 120 上转型对象调用的一定是子类重写的getM()方法,此时子类B的m=20,所以返回120
System.out.println(b.seeM()); // -100 子类继承的seeM()方法操作的m是被子类隐藏的m,即A中的m
}
}
5.1阅读程序
- 15.0 8.0
- 11 110
- 98.0 12 98.0 9
- 120 120 -100
5.2编程题
public abstract class Animal {
public abstract void cry();
public abstract String getAnimalName();
}
public class Dog extends Animal {
@Override
public void cry() {
System.out.println("旺旺旺");
}
@Override
public String getAnimalName() {
return "Dog";
}
}
public class Cat extends Animal {
@Override
public void cry() {
System.out.println("喵喵喵");
}
@Override
public String getAnimalName() {
return "Cat";
}
}
public class Simulator {
public void playSound(Animal animal) {
System.out.println(animal.getAnimalName() + "叫:");
animal.cry();
}
}
public class main {
public static void main(String[] args) {
Simulator simulator = new Simulator();
simulator.playSound(new Dog()); //Dog叫:旺旺旺
simulator.playSound(new Cat()); // Cat叫:喵喵喵
}
}
6.接口与实现
前情知识回顾:
接口里面没有构造函数,也产生class类
接口体中只有常量和抽象方法两部分,访问权限都是public
,常量允许public、final、static修饰,方法允许public、abstract修饰
接口声明:
interface
xxx
实现接口:class Aimplements
xxx
抽象类既可以重写接口中的方法,也可以直接拥有接口中的方法
接口默认为友好接口(可以被与该接口在同一包中的类实现),可以加public
修饰,这样可以被任何一个类实现
接口可以被继承子接口继承父类中所有方法和常量
接口多态:
同一个接口,不同的类具体实现方法可以不同
abstract
类和接口比较:
- 接口中只有常量,
abstract
类可以有常量,也可有变量- 均可以有
abstract
方法abstract
类可以有非abstract
方法,但接口不行
6.1选择题
- D 允许接口中只有一个抽象方法
- A B (A不可用protected修饰 B 方法只能是public、abstract修饰
- A
6.2阅读程序
- 15.0 8
- 18 15
6.3编程题
package com.example.six;
public interface Animal {
public void cry();
public String getAnimalName();
}
package com.example.six;
public class Simulator {
public void playSound(Animal animal) {
System.out.println(animal.getAnimalName() + "叫:");
animal.cry();
}
}
package com.example.six;
public class Dog implements Animal {
@Override
public void cry() {
System.out.println("旺旺旺");
}
@Override
public String getAnimalName() {
return "Dog";
}
}
package com.example.six;
public class Cat implements Animal{
@Override
public void cry() {
System.out.println("喵喵喵");
}
@Override
public String getAnimalName() {
return "Cat";
}
}
package com.example.six;
public class main {
public static void main(String[] args) {
Simulator simulator = new Simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
}
}
7.内部类与异步类
前情知识回顾:
匿名类只能是内部类
内部类的类体中不能声明类变量(static)和类方法
内部类的外嵌类的成员变量在内部类依然有效
内部类中的方法也可以调用外嵌类中的 方法
内部类仅供他的外嵌类使用。
在匿名内部类中,必须实现抽象方法或接口方法,否则会报告错误,即匿名类可以实例化
匿名的内部类不能extends(继承)其它类,但一个内部类可以作为一个接口,由另一个内部类实现。
7.1阅读程序
- 大家好,祝工作顺利!(是直接执行的内部类中的cry)
- p是接口变量
- 你好 fine thanks
- 我是红牛
7.2编程题
断言语句:(需要设置,默认不执行)Run->Edit Configureations->VM options: -ea
package com.example.six;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double sum = 0;
int m = 0;
while(reader.hasNextDouble()) {
Double num = reader.nextDouble();
assert num <= 100 && num >= 0:"输入的成绩非法!";
m = m + 1;
sum = sum + num;
}
System.out.println(m + "个数的和为" + sum);
System.out.println(m + "个数的平均值为" + sum / m);
}
}
8.常用实用类
8.1前置知识
String对象是final类,即String类不可以有子类。
string对象的字符序列不可修改
常量池:两个常量相同,则引用相 同。
动态区:两个对象变量实体相同,但引用不同
string.equals()比较的是两个对象的实体是否相同,但是’==’ 比较的是两个对象的引用是否相同
StringBuffer类
append,
8.2阅读程序
- 苹果
- Love:Game
number=4
s = ['We' ,'Love' ,'This' ,'Game']
StringTokenizer(str) 分隔字符串,默认空格
- 15 abc我们
一个中文两个byte
- 13579
- 9javaHello
\\djava\\w{1,}
=> 一个数字开头+java+一个以上字符 的字符串
\\d
就是\d,匹配一位数字\\w
就是\w,匹配字母或数字或下划线或汉字等{1, }
重复1次或更多次
- ,
package com.example.six;
import java.util.*;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
String s = String.format("%tF(%<tA)",calendar);
System.out.println(s);
int n = 25;
System.out.println("向后滚动(在月内)" + n + "天");
/*
不应该通过类实例访问静态成员
*/
calendar.roll(calendar.DAY_OF_MONTH, n);
s = String.format("%tF(%<ta)",calendar);
System.out.println(s);
System.out.println("再向后滚动(在年内)" + n + "天");
calendar.roll(calendar.DAY_OF_YEAR, n);
s = String.format("%tF(%<ta)",calendar);
System.out.println(s);
}
}
/*
2022-05-05(星期四)
向后滚动(在月内)25天
2022-05-30(星期一)
再向后滚动(在年内)25天
2022-06-24(星期五)
*/
- 基本上没有消耗内存
package com.example.six;
import java.util.*;
public class Main {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
long free = runtime.freeMemory();
System.out.println("Java虚拟机可用空闲内存" + free + "bytes");
long total = runtime.totalMemory();
System.out.println("Java虚拟机占用总内存" + total + "bytes");
long n1 = System.currentTimeMillis();
for(int i = 1; i <= 100; i++) {
int j = 2;
for(; j < i / 2; j++) {
if(i % j == 0) {
break;
}
if(j > i / 2) {
System.out.println(" " + i);
}
}
}
long n2 = System.currentTimeMillis();
System.out.println("\n循环用时:" + (n2 - n1) + "毫秒\n");
free = runtime.freeMemory();
System.out.println("Java虚拟机可用空闲内存" + free + "bytes");
total = runtime.totalMemory();
System.out.println("Java虚拟机占用总内存" + total + "bytes");
}
}
/*
Java虚拟机可用空闲内存188345056bytes
Java虚拟机占用总内存191365120bytes
循环用时:0毫秒
Java虚拟机可用空闲内存188345056bytes
Java虚拟机占用总内存191365120bytes
*/
8.3编程题
8.3.1
public class Main {
public static void main(String[] args) {
String str1 = "Come On Forever!";
System.out.println(str1.toUpperCase());
System.out.println(str1.toLowerCase());
System.out.println(str1.concat("Fredoom!"));
}
}
8.3.2
public class Main {
public static void main(String[] args) {
String str1 = "Come On Forever!";
System.out.println(str1 + "的第一个字符是:" + str1.charAt(0));
System.out.println(str1 + "的最后一个字符是:" + str1.charAt(str1.length() - 1));
}
}
"""
Come On Forever!的第一个字符是:C
Come On Forever!的最后一个字符是:!
8.3.3
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.YEAR, Integer.parseInt(args[0]));
calendar1.set(Calendar.MONTH, Integer.parseInt(args[1]));
calendar1.set(Calendar.DAY_OF_MONTH, Integer.parseInt(args[2]));
Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.YEAR, Integer.parseInt(args[3]));
calendar2.set(Calendar.MONTH, Integer.parseInt(args[4]));
calendar2.set(Calendar.DAY_OF_MONTH, Integer.parseInt(args[5]));
long time1 = calendar1.getTimeInMillis();
long time2 = calendar2.getTimeInMillis();
long subDay = (time1 - time2) / (1000 * 60 * 60 * 24);
System.out.println(new Date(time1) + " and " + new Date(time2) + "be apart " + subDay + " days.");
}
}
"""
D:\idea_project\class_work\homework\src\com\example\six>javac Main.java
> cd ../
> cd ../
D:\idea_project\class_work\homework\src>java com.example.six.Main 2022 5 19 2003 4 20
Sun Jun 19 09:12:41 CST 2022 and Tue May 20 09:12:41 CST 2003be apart 6969 days.
"""
8.3.4
Math类的常用方法:
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
double num1 = 5.0;
double num2 = 5.2;
double num3 = 5.9;
double num4 = 5.6;
double st = Math.sqrt(num1);
System.out.println(num1 + "的平方根:" + st);
System.out.println("大于等于 "+ num2 + "的最小整数:" + (int)Math.ceil(num2));
System.out.println("小于等于 "+ -num2 + "的最小整数:" + (int)Math.floor(-num2));
System.out.println(num3+ "四舍五入的整数: " + Math.round(num3));
System.out.println(-num4+ "四舍五入的整数: " + Math.round(-num4));
BigInteger result = new BigInteger("0");
BigInteger one = new BigInteger("123456789");
BigInteger two = new BigInteger("987654321");
result = one.add(two);
System.out.println(one + " + " + two + "的和为:" + result);
result = one.multiply(two);
System.out.println(one + " + " + two + "的积为:" + result);
}
}
"""
5.0的平方根:2.23606797749979
大于等于 5.2的最小整数:6
小于等于 -5.2的最小整数:-6
5.9四舍五入的整数: 6
-5.6四舍五入的整数: -6
123456789 + 987654321的和为:1111111110
123456789 + 987654321的积为:121932631112635269
"""
8.3.5
public class Main {
public static void main(String[] args) {
String target = "Happy 420 Birthday to you! 519";
String regex = "\\D+"; // 匹配非数字
String[] digitWord = target.split(regex);
for(String s : digitWord) {
System.out.println(s) ;
}
System.out.println(digitWord.length); // length=3, ["","420","519"]
}
}
8.3.6
import java.util.InputMismatchException;
import java.util.Scanner;
public class GetPrice {
int len = 0;
double sum = 0;
public double getSum(String cost) {
String regex = "[^0123456789.]+";
Scanner scanner = new Scanner(cost);
scanner.useDelimiter(regex);
while (scanner.hasNext()) {
try {
double price = scanner.nextDouble();
len++;
sum += price;
} catch (InputMismatchException exp) {
String t = scanner.next();
}
}
return sum;
}
public double getAvg() {
return sum / len;
}
}
public class Main {
public static void main(String[] args) {
String message = "数学87分,物理76分,英语96分";
GetPrice getPrice = new GetPrice();
System.out.println("总成绩为::" + getPrice.getSum(message));
System.out.println("平均分数为::" + getPrice.getAvg());
}
}
9.组件及事件处理
前情回顾:
JFrame类的对象的默认布局是BoradLayout布局
一个容器对象不能使用add方法添加一个JFrame窗口
JTextArea中的文档对象可以触发ActionEvent事件
MouseListener接口中有5个方法
9.1编程题
9.1.1
编写应用程序,有一个标题为“计算”的窗口,窗口的布局为FlowLayout布局。窗口中添加两个文本区,当我们在一个文本区中输入若干个数时,另一个文本区同时对输入的数进行求和运算并求出平均值,也就是随着输入的不断变化,另一个文本区不断更新求和以及平均值。
public class Main {
public static void main(String[] args) {
ComputeWindow win = new ComputeWindow();
win.setBounds(100,100,600,600);
win.setTitle("计算");
}
}
import javax.swing.*;
import java.awt.*;
public class ComputeWindow extends JFrame {
JTextArea inputText,showText;
TextListener textChangeListener;
ComputeWindow() {
init();
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void init() {
inputText = new JTextArea(15,20);
showText = new JTextArea(15,20);
showText.setLineWrap(true);
showText.setWrapStyleWord(true);
add(new JScrollPane(inputText));
add(new JScrollPane(showText));
showText.setEditable(false);
textChangeListener = new TextListener();
textChangeListener.setInputText(inputText);
textChangeListener.setShowText(showText);
(inputText.getDocument()).addDocumentListener(textChangeListener);
}
}
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.util.Scanner;
public class TextListener implements DocumentListener {
JTextArea inputText,showText;
double sum;
double avg;
int cnt;
@Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
String str = inputText.getText();
sum = 0; // 注意在这里需要全部初始化,不然每打一个空格,所有数的和或者平均值都会变化
avg = 0;
cnt = 0;
Scanner scanner = new Scanner(str);
while(scanner.hasNextDouble()) {
cnt++;
sum += scanner.nextDouble();
}
avg = sum / cnt;
showText.setText(null);
showText.append("\n和为:" + sum);
showText.append("\n平均值为:" + avg);
}
public void setInputText(JTextArea text) {
inputText = text;
}
public void setShowText(JTextArea text) {
showText = text;
}
}
9.1.2
public class Main {
public static void main(String[] args) {
ComputeWindow win = new ComputeWindow();
win.setBounds(100,100,600,600);
win.setTitle("计算");
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ComputeWindow extends JFrame implements ActionListener {
JTextField inputField1, inputField2, outputFiled;
JLabel label;
JPanel panel;
Box vbox;
JButton buttonAdd, buttonSub, buttonMul, buttonDiv;
ComputeWindow() {
init();
setContentPane(panel);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
inputField1 = new JTextField(10);
inputField2 = new JTextField(10);
outputFiled = new JTextField(10);
label = new JLabel("=");
label.setBackground(Color.green);
vbox = Box.createVerticalBox();
panel = new JPanel();
buttonAdd = new JButton("加");
buttonSub = new JButton("减");
buttonMul = new JButton("乘");
buttonDiv = new JButton("除");
buttonAdd.addActionListener(this);
buttonSub.addActionListener(this);
buttonMul.addActionListener(this);
buttonDiv.addActionListener(this);
vbox.add(buttonAdd);
vbox.add(buttonSub);
vbox.add(buttonMul);
vbox.add(buttonDiv);
panel.add(inputField1);
panel.add(vbox);
panel.add(inputField2);
panel.add(label);
panel.add(outputFiled);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonAdd) {
try {
double a = Double.parseDouble(inputField1.getText());
double b = Double.parseDouble(inputField2.getText());
double result = a + b;
outputFiled.setText("" + result);
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(this,"你输入了非法数字","消息对话框",JOptionPane.WARNING_MESSAGE);
}
} else if(e.getSource() == buttonSub) {
try {
double a = Double.parseDouble(inputField1.getText());
double b = Double.parseDouble(inputField2.getText());
double result = a - b;
outputFiled.setText("" + result);
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(this,"你输入了非法数字","消息对话框",JOptionPane.WARNING_MESSAGE);
}
} else if(e.getSource() == buttonMul) {
try {
double a = Double.parseDouble(inputField1.getText());
double b = Double.parseDouble(inputField2.getText());
double result = a * b;
outputFiled.setText("" + result);
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(this,"你输入了非法数字","消息对话框",JOptionPane.WARNING_MESSAGE);
}
} else if(e.getSource() == buttonDiv) {
try {
double a = Double.parseDouble(inputField1.getText());
double b = Double.parseDouble(inputField2.getText());
double result = a / b;
outputFiled.setText("" + result);
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(this,"你输入了非法数字","消息对话框",JOptionPane.WARNING_MESSAGE);
}
}
}
}
9.1.3
public class Main {
public static void main(String[] args) {
WindowTrapezoid win = new WindowTrapezoid();
win.setBounds(100,100,420,260);
win.setTitle("使用MVC结构计算梯形面积");
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WindowTrapezoid extends JFrame implements ActionListener {
Trapezoid trapezoid;
JTextField textFieldA,textFieldB,textFieldC;
JTextArea showArea;
JButton controlButton;
WindowTrapezoid() {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
trapezoid = new Trapezoid();
textFieldA = new JTextField(5);
textFieldB = new JTextField(5);
textFieldC = new JTextField(5);
showArea = new JTextArea();
controlButton = new JButton("计算面积");
JPanel pNorth = new JPanel();
pNorth.add(new JLabel("上底:"));
pNorth.add(textFieldA);
pNorth.add(new JLabel("下底:"));
pNorth.add(textFieldB);
pNorth.add(new JLabel("高:"));
pNorth.add(textFieldC);
pNorth.add(controlButton);
controlButton.addActionListener(this);
add(pNorth, BorderLayout.NORTH);
add(new JScrollPane(showArea), BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
double upperBottom = Double.parseDouble(textFieldA.getText().trim());
double belowBottom = Double.parseDouble(textFieldB.getText().trim());
double height = Double.parseDouble(textFieldC.getText().trim());
trapezoid.setUpperBottom(upperBottom);
trapezoid.setBelowBottom(belowBottom);
trapezoid.setHeight(height);
String area = trapezoid.getArea();
showArea.append("梯形的上底为:" + upperBottom + ",下底为:" + belowBottom + ",高为:" + height + ",所以面积为:");
showArea.append(area + "\n");
} catch (Exception exception){
showArea.append("\n" + exception + "\n");
}
}
}
public class Trapezoid {
double uBottom,bBottom,h,area;
public void setUpperBottom(double upperBottom) {
uBottom = upperBottom;
}
public void setBelowBottom(double belowBottom) {
bBottom = belowBottom;
}
public void setHeight(double height) {
h = height;
}
public String getArea() {
area = (bBottom + uBottom) * h / 2.0;
return String.valueOf(area);
}
}
10.输入、输出流
10.1阅读程序
-
51 0
-
3 abc 1 dbc
public class Main {
public static void main(String[] args) {
File file = new File("D:\\idea_project\\class_work\\homework\\src\\com\\example\\six\\Main.java");
try {
RandomAccessFile in = new RandomAccessFile(file,"rw");
System.out.println(file.length()); // 579
FileOutputStream out = new FileOutputStream(file);
System.out.println(file.length()); // 0
} catch (IOException e) {
System.out.println("File read error" + e);
}
}
}
import java.io.*;
public class Main {
public static void main(String[] args) {
int n = -1;
File file = new File("D:\\idea_project\\class_work\\homework\\src\\com\\example\\six\\hello.txt");
byte[] a = "abcd".getBytes();
try {
FileOutputStream out = new FileOutputStream(file);
out.write(a);
out.close();
FileInputStream in = new FileInputStream(file);
byte[] tom = new byte[3];
int m = in.read(tom,0,3);
System.out.println(m); // 3
String s = new String(tom,0,3);
System.out.println(s); // abc
m = in.read(tom,0,3);
System.out.println(m); // 1
s = new String(tom,0,3);
System.out.println(s); // dbc
} catch (IOException e) {
System.out.println("File read error" + e);
}
}
}
public class Main {
public static void main(String[] args) {
File file = new File("D:\\idea_project\\class_work\\homework\\src\\com\\example\\six\\hello.txt");
try {
FileOutputStream out = new FileOutputStream(file);
PrintStream printStream = new PrintStream(out);
printStream.print(12345.6789);
printStream.println("how are you");
printStream.println(true);
printStream.close();
} catch (IOException e) {
}
}
}
10.2编程题
10.2.1
public class Main {
public static void main(String[] args) {
File file = new File("D:\\idea_project\\class_work\\homework\\src\\com\\example\\six\\hello.txt");
try {
RandomAccessFile in = new RandomAccessFile(file,"rw");
in.seek(0);
long m = in.length();
while (m >= 0) {
m -= 1;
in.seek(m);
int c = in.readByte();
if(c <= 255 && c > 0) {
System.out.print((char)c);
} else {
m -= 1;
in.seek(m);
byte[] cc = new byte[2];
in.readFully(cc);
System.out.print(new String(cc));
}
}
} catch (IOException e) {
}
}
}
/*
12345.6789how are you
true
☟☟☟
eurt
uoy era woh9876.54321
*/
10.2.2
import java.io.*;
public class Main {
public static void main(String[] args) {
File file1 = new File("D:\\idea_project\\class_work\\homework\\src\\com\\example\\six\\Main.java");
File file2 = new File("D:\\idea_project\\class_work\\homework\\src\\com\\example\\six\\hello.txt");
try {
FileReader inOne = new FileReader(file1);
BufferedReader inTwo = new BufferedReader(inOne);
FileWriter toFile = new FileWriter(file2);
BufferedWriter out = new BufferedWriter(toFile);
String s = null;
int i = 0;
s = inTwo.readLine();
while (s != null) {
i++;
out.write(i + " " + s);
out.newLine();
s = inTwo.readLine();
}
inOne.close();
inTwo.close();
out.flush();
out.close();
toFile.close();
} catch (IOException e) {
}
}
}
10.2.3
public class Main {
public static void main(String[] args) {
File file = new File("D:\\idea_project\\class_work\\homework\\src\\com\\example\\six\\student.txt");
Scanner sc = null;
int count = 0;
double sum = 0;
try {
double score = 0;
sc = new Scanner(file);
sc.useDelimiter("[^123456789.]+");
while (sc.hasNextDouble()) {
score = sc.nextDouble();
count++;
sum += score;
System.out.println(score);
}
System.out.println("平均价格:" + sum / count);
} catch (Exception exp) {
System.out.println(exp);
}
}
}
11.JDBC与MySQL数据库操作
11.1编程题
11.1.1
按出生日期排序mess表的记录。
public class Home {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test_homework?useSSL=true&characterEncoding=utf-8";
String user = "xx";
String password = "xxxxx";
try {
Connection connection = DriverManager.getConnection(url, user, password);
Statement sql = connection.createStatement();
ResultSet res = sql.executeQuery("select * from mess order by birthday");
while (res.next()) {
String number = res.getString(1);
String name = res.getString(2);
Date date = res.getDate(3);
float height = res.getFloat(4);
System.out.printf("%s\t" , number);
System.out.printf("%s\t" , name);
System.out.printf("%s\t" , date);
System.out.println(height);
}
connection.close();
} catch (SQLException throwables) {
System.out.println(throwables);
}
}
}
11.1.2
// Home.java
import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Home {
public static void main(String[] args) throws IOException {
String[] tableHead;
String[][] content;
JTable table;
JFrame win = new JFrame();
Query findRecord = new Query();
System.out.println("请输入数据库名和表名并以空格分割(一行内):");
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
String[] input = buffer.readLine().split(" ");
String dataBaseName = input[0];
String tableName = input[1];
findRecord.setDatabaseName(dataBaseName);
findRecord.setSQL("select * from " + tableName);
content = findRecord.getRecord();
tableHead = findRecord.getColumnName();
table = new JTable(content,tableHead);
win.add(new JScrollPane(table));
win.setBounds(12,100,400,200);
win.setVisible(true);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
// Query.java
import java.sql.*;
public class Query {
String databaseName="";
String SQL;
String[] columnName;
String[][] record;
public Query() {}
public void setDatabaseName(String s) {
databaseName = s.trim();
}
public void setSQL(String SQL) {
this.SQL = SQL.trim();
}
public String[] getColumnName() {
if(columnName == null) {
System.out.println("先查询记录");
return null;
}
return columnName;
}
public String[][] getRecord() {
startQuery();
return record;
}
private void startQuery() {
Connection con;
ResultSet res;
Statement sql;
String url = "jdbc:mysql://localhost:3306/"+databaseName+"?useSSL=true&characterEncoding=utf-8";
try {
con = DriverManager.getConnection(url,"root","203420");
sql = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
res = sql.executeQuery(SQL);
ResultSetMetaData metaData = res.getMetaData();
int columnCount = metaData.getColumnCount();
columnName = new String[columnCount];
for(int i = 1; i <= columnCount; i++) {
columnName[i - 1] = metaData.getColumnName(i);
}
res.last();
int recordAmount = res.getRow();
record = new String[recordAmount][columnCount];
int i = 0;
res.beforeFirst();
while (res.next()) {
for(int j = 1; j <= columnCount; j++) {
record[i][j - 1] = res.getString(j);
}
i++;
}
con.close();
} catch (SQLException throwables) {
System.out.println("请输入正确的表名" + throwables);
}
}
}
12.Java多线程机制
12.1阅读程序
12.1.1
这里是两个线程同时,交叉输出yes和ok
// Home.java
public class Home {
public static void main(String[] args) {
Target target = new Target();
Thread thread = new Thread(target);
thread.start();
for(int i = 0; i <= 10; i++) {
System.out.println("yes");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Target.java
public class Target implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
System.out.println("ok");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
12.1.2
这里是单线程,先输出11个ok,在输出11个yes
// Home.java
public class Home {
public static void main(String[] args) {
Target target = new Target();
Thread thread = new Thread(target);
thread.run();
for(int i = 0; i <= 10; i++) {
System.out.println("yes");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Target.java
public class Target implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
System.out.println("ok");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
12.1.3
// Home.java
public class Home {
public static void main(String[] args) {
Target target = new Target();
Thread thread1 = new Thread(target);
Thread thread2 = new Thread(target);
thread1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
thread2.start();
}
}
}
// Target.java
public class Target implements Runnable {
int i = 0;
@Override
public void run() {
i++;
System.out.println("i=" + i);
}
}
// i=1
12.1.4
public class Home {
public static void main(String[] args) {
Target target1 = new Target();
Target target2 = new Target();
Thread thread1 = new Thread(target1);
Thread thread2 = new Thread(target2);
thread1.start();
try {
Thread.sleep(1000);
} catch (Exception e) {
thread2.start();
}
}
}
// i=1
12.1.5
public class Home {
public static void main(String[] args) {
javax.swing.Timer time = new javax.swing.Timer(500,new A());
time.setInitialDelay(0);
time.start();
}
}
// A.java
import javax.swing.*;
import java.util.Date;
public class A extends JLabel implements java.awt.event.ActionListener {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
System.out.println(new Date());
}
}
12.1.6
public class A implements java.awt.event.ActionListener {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
System.out.println(new Date());
}
}
// 直接退出了,计时器启动失败
12.1.7
public class A implements Runnable {
Thread t1,t2;
StringBuffer buffer = new StringBuffer();
A() {
t1 = new Thread(this);
t2 = new Thread(this);
}
public synchronized void addChar(char c) {
if(Thread.currentThread() == t1) {
while (buffer.length() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer.append(c);
}
if(Thread.currentThread() == t2) {
buffer.append(c);
notifyAll();
}
}
@Override
public void run() {
if(Thread.currentThread() == t1) {
addChar('A');
}
if(Thread.currentThread() == t2) {
addChar('B');
}
}
public static void main(String[] args) {
A hello = new A();
hello.t1.start();
hello.t2.start();
while(hello.t1.isAlive() || hello.t2.isAlive()) {
}
System.out.println(hello.buffer);
}
}
// BA
// 线程2启动之后在通知线程1
12.1.8
public class Bank implements Runnable {
Thread t1,t2;
Bank() {
t1 = new Thread(this);
t2 = new Thread(this);
}
@Override
public void run() {
printMess();
}
public void printMess() {
System.out.println(Thread.currentThread().getName() + "正在使用这个方法");
synchronized (this) {
// 当一个线程使用同步块时,其他线程必须等待
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "正在使用这个同步块");
}
}
}
public static void main(String[] args) {
Bank hello = new Bank();
hello.t1.start();
hello.t2.start();
}
}
// Thread-1正在使用这个方法
// Thread-0正在使用这个方法
13.Java网络编程
13.1问答题
- 一个URL对象通常包括哪些方法?
map.put("协议", url.getProtocol());
map.put("主机名称", url.getHost());
map.put("请求端口", url.getPort());
map.put("请求默认端口", url.getDefaultPort());
map.put("请求路径", url.getPath());
map.put("请求参数", url.getQuery());
map.put("请求文件", url.getFile());
map.put("认证信息", url.getAuthority());
map.put("用户信息", url.getUserInfo());
map.put("引用信息", url.getRef());
- URL对象调用哪个方法可以返回一个指向该URL对象所包含的资源的输入流?
InputStream openStream()
方法
- 客户端的Socket对象和服务器端的Scoket对象时怎样通信的?
服务器建立ServerSocket
对象,ServerSocket
对象负责等待客户端请求建立套接字连接,而客户端建立Socket
对象向服务器发出套接字连接请求。客户端的套接字对象和服务器端的通过输入流和输出流连接在一起。
- ServerSocket对象调用accept方法返回一个什么类型的对象?
返回一个和客户端Socket
对象相连接的Socket
对象。
- InetAddress对象使用怎样的格式来表示自己封装的地址信息?
www.sina.com.cn/202.108.37.40
(含有主机地址的域名和IP地址)
14.图形、图像与音频
15.泛型与集合框架
15.1问答题
1.LinkedList链表和ArrayList数组表有什么不同?
LinkedList采用链表存储,底层使用的是 双向链表数据结构;ArrayList采用数组存储,底层使用的是 Object[] 数组。
LinkedList 不支持高效的随机元素访问,而 ArrayList 支持。
2.为何使用迭代器遍历链表?
迭代器用于提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
在遍历链表时,可以使用迭代器达到快速遍历集合的目的。(由于链表的存储结构不是顺序结构,因此,链表调用get(int index)方法的速度比顺序存储结构的集合慢)
3.树集的结点是按添加的先后顺序排列的吗?
不是,树节点中的数据会按照数据的大小顺序一层一层地依次排列,在同一层中的结点从左到右按字典序从小到大递增排列,下一层的都比上一层的小。
4.对于经常需要查找的数据,应当选用LinkedList,还是选用HashMap<K,V>来存储?
HashMap<K,V>,减少检索的开销。