12)System.out" />

java课后习题答案

第1章 了解Java

1. 编写一个程序,将用户在命令行输入的24小时制时间转换为12小时制。

public class TimeTest{
public static void main(String args[]){
int time;
time = Integer.parseInt(args[0]);
if(time<0||time>24)
System.out.println("输入的不是一个合法时间!");
else if(time>12)
System.out.println("12小时制为"+(time-12)+"点");
else
System.out.println("12小时制为"+time+"点");
}
}

2. 用户输入x的数值,根据如下规则输出计算后的结果y值。
x (x<1)
Y = 2x -1 (1<=x<10)
3x -11 (x>=10)

public class CalculateTest{
public static void main(String args[]){
float x,y;
x = Float.parseFloat(args[0]);
if(x<1)
y = x;
else if(1<=x&&x<10)
y = 2*x-1;
else
y = 3*x-11;
System.out.println(y);
}
}

3. 编写一个Java应用程序,由命令行参数输入一个百分制成绩,要求打印出成绩等级“A”、“B”、“C” 、“D”、 “E”。90分以上为“A”;80~89分为“B”;70~79分为“C”;60~69分为“D”;60分以下为“E”。
要求使用switch语句实现。
运行效果如图2所示:

图1
public class PrintGrade {
public static void main(String[] args) {
double score = Double.parseDouble(args[0]);
if(score<0 || score>100)
System.out.println("错误,不是一个合法的百分制成绩!");
else{
int s = ((int)score)/10;
char grade;
switch(s){
case 10:
case 9: grade = 'A'; break;
case 8: grade = 'B'; break;
case 7: grade = 'C'; break;
case 6: grade = 'D'; break;
default:grade = 'E';
}
System.out.println("成绩是:"+score+",相应的等级是"+grade);
}
}
}

4. 假设今天是星期日,编写一个程序,求n天后是星期几。要求:n的数值由命令行输入;使用switch语句实现。

public class DateTest {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
switch (n%7){
case 0: System.out.println(n+"天后是星期天"); break;
case 1: System.out.println(n+"天后是星期一"); break;
case 2: System.out.println(n+"天后是星期二"); break;
case 3: System.out.println(n+"天后是星期三"); break;
case 4: System.out.println(n+"天后是星期四"); break;
case 5: System.out.println(n+"天后是星期五"); break;
case 6: System.out.println(n+"天后是星期六"); break;
}
}
}

5. 用户在命令行输入一个数字,按照数字输出相应个数的星号。

public class PrintStar {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int i;
for( i=1; i<=n; i++)
System.out.print("*");
System.out.println();
}
}

6. 编写程序,求0到100之间的偶数和。
要求:分别用while语句、do while语句和for循环语句实现。

while实现:
public class SumDemo1 {
public static void main(Stri

ng[] args) {
int sum = 0, i = 0;
while(i<=100){
if(i%2==0)
sum = sum+i;
i++;
}
System.out.println("0--100之间所有偶数的和是"+sum);
}
}

do while实现:
public class SumDemo2 {
public static void main(String[] args) {
int sum = 0, i = 0;
do{
if(i%2==0)
sum = sum+i;
i++;
}while(i<=100);
System.out.println("0--100之间所有偶数的和是"+sum);
}
}

for循环实现:
public class SumDemo3 {
public static void main(String[] args) {
int sum = 0, i = 0;
for( ; i<=100; i=i+2)
sum = sum+i;
System.out.println("0--100之间所有偶数的和是"+sum);
}
}

7. 输入一个大于1的整数,求1到这个数的阶乘。用三种循环语句实现。
提示:5的阶乘表示为5!,计算公式:5!=1*2*3*4*5

while实现:
public class Factorial1 {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
int result = 1;
if(num<1)
System.out.println("应输入大于1的整数!");
else{
int i = 1;
while(i<=num){
result = result*i;
i++;
}
System.out.println(num+"的阶乘是"+result);
}
}
}

do while实现:
public class Factorial2 {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
int result = 1;
if(num<1)
System.out.println("应输入大于1的整数!");
else{
int i = 1;
do{
result = result*i;
i++;
}while(i<=num);
System.out.println(num+"的阶乘是"+result);
}
}
}
for循环实现:
public class Factorial3 {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
int result = 1;
if(num<1)
System.out.println("应输入大于1的整数!");
else{
int i;
for( i=1; i<=num; i++)
result = result*i;
System.out.println(num+"的阶乘是"+result);
}
}
}

8. 用for循环语句打印九九乘法表。

public class Multiplication {
public static void main(String[] args) {
int i,j;
for(i=1;i<=9;i++){
for(j=1;j<=i;j++)
System.out.print(i*j+"\t");
System.out.println();
}
}
}

第2章 面向对象的“对象”

1. 定义一个描述长方体的类Box,类中有三个整型的成员变量:length、width和height,分别表示长方体的长、宽和高。定义setInfo(int ,int ,int)方法设置这三个变量的值;定义volumn()方法求长方体的体积并返回整型结果;定义area()方法求长方体的表面积并返回整型结果;定义toString()方法把长方体的长、宽、高,以及长方体的体积和表面积转化为字符串并返回字符串。
编写Java应用程序,测试类Box,使用类中定义的各个方法,并将其结果输出。

class Box{
int length,width,height;
public setInfo(int l,int w,int h){
length = l;
width = w;
height = h;
}
public int volumn(){
return length*width*height;
}
public int area(){
return (length*width + length*

height + width*height) * 2;
}
public String toString(){
return "Length:" + length + " width:" + width + " height:" + height
+ " volumn: " + volumn() + " area:" + area();
}
}

public class BoxTest {
public static void main(String[] args) {
Box b = new Box();
b.setInfo(5,2,4);
System.out.println(b.toString());
}
}

2. 定义一个圆形类Circle,类中有一个用来描述半径的double型成员变量r,定义setR(double)方法初始化半径;定义getArea()方法求圆形的面积并返回double类型结果;定义getPerimeter()方法求圆形的周长并返回double类型结果。
编写Java应用程序,使用Circle类创建两个对象,通过相应方法分别设置不同的半径值,计算各自的面积及周长并显示结果。

class Circle {
double r;

void setR(double radius){
r = radius;
}

double getArea(){
return 3.14*r*r;
}

double getPerimeter(){
return 2*3.14*r;
}
}
public class CircleTest {

public static void main(String[] args) {

Circle c1 = new Circle();
Circle c2 = new Circle();

c1.setR(1);
c2.setR(2);

System.out.println("c1的面积是"+c1.getArea()+
",c1的周长是"+c1.getPerimeter());
System.out.println("c2的面积是"+c2.getArea()+
",c2的周长是"+c2.getPerimeter());
}

}


第3章 对象的属性---变量详述

1.编写程序,计算如下表达式的值,将结果输出。
(1) 3.5+1/2+56%10
(2) 3.5+1.0/2+56%10
(3) int a = 4%3*7+1

public class Test{
public static void main(String[] args) {
System.out.println( 3.5+1/2+56%10 );
System.out.println( 3.5+1.0/2+56%10 );
int a = 4%3*7+1;
System.out.println( a );
}
}
程序运行结果:
9.5
10.0
8

2.思考下列语句执行后变量a、b、c、d的值分别是多少:
int a=5,b=8,c,d;
c=(a++)*b;
d=(++a)*b;

执行后的结果是:
a=7 b=8 c=40 d=56

3.自定义一个字符串数组,提示用户输入5个字符串,通过循环语句实现将用户输入的字符串存放到数组里,然后反向输出这五个字符串。

import java.util.Scanner;

public class Test{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String str[] = new String[5];
int i;
for(i=0;i<5;i++){
System.out.println("请输入第"+(i+1)+"个字符串");
str[i] = reader.next();
}
System.out.println("反向输出这5个字符串:");
for(i=4;i>=0;i--)
System.out.println(str[i]);
}
}

4.定义一个实型数组用来存放学生成绩,提示用户确定成绩的个数,根据个数创建数组。提示用户输入每个成绩,为各数组元素赋值。询问用户要查找第几个同学的成绩,显示相应的查询结果,如果超出个数范围则进行相应提示。

import java.util.*;

public class Search1 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double sc

ore[];
System.out.println("您要输入多少个同学的成绩?");
int num = reader.nextInt();
score = new double[num];
for(int i=0;iSystem.out.println("请输入第"+(i+1)+"个同学的成绩");
score[i] = reader.nextDouble();
}
System.out.println("您要查找第几个同学的成绩?");
int index = reader.nextInt();
if( index>=1 && index<=num-1 )
System.out.println("第" + index +
"个同学的成绩是"+score[index-1]);
else
System.out.println("数据不在合法范围内,无法查找。");
}

}

5.在第4题的基础上进行改写,修改查询条件:询问用户要查找分数为多少的成绩,找到相应的成绩则显示第几位同学符合查询条件,找不到相应的成绩则显示没有该成绩,如果超出成绩范围则进行相应提示。

import java.util.*;

public Search2{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double score[];
System.out.println("您要输入多少个同学的成绩?");
int num = reader.nextInt();
score = new double[num];
for(int i=0;iSystem.out.println("请输入第"+(i+1)+"个同学的成绩");
score[i] = reader.nextDouble();
}
System.out.println("您要查找的成绩是?");
double s = reader.nextDouble();
boolean flag = false;
if(s>=0 && s<=100){
for(int i=0;iif(score[i]==s){
System.out.println("第"+(i+1)+"个同学符合查询条件");
flag = true;
}
}
if(!flag)
System.out.println("没有学生考该分数成绩");
}
else
System.out.println("成绩非法,不能查询。");
}
}

6.提示用户输入一个整数,再提示用户输入一个符号。在屏幕上输出该整数个这样的符号。

import java.util.*;

class CharTest{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
System.out.println("请输入一个整数");
int n = reader.nextInt();
System.out.println("请输入一个符号");
char ch = reader.next().charAt(0);
for(int i = 1; i<=n ;i++)
System.out.print(ch);
System.out.println();
}
}


第4章 对象的行为---成员方法详述

1. 编写Java应用程序,定义一个计算两个整数和的方法static int add(int op1, int op2)。在main方法中声明两个整型变量,分别赋值,调用add()方法得到它们的和,在屏幕上输出结果。

public class AddTest {
public static void main(String[] args) {
int num1,num2;
num1 = 10;
num2 = 20;
System.out.println(num1 + "+" + num2 + "=" + add(num1,num2));
}

static int add(int op1,int op2){
return op1+op2;
}
}

2. 编写程序,定义一个方法public static void abs(int a),用来求绝对值并输出结果。在main方法中从命令行读入一个整数,调用这个结果求它的绝对值。

import java.util.Scanner;

public class Demo{
public static void main(String[]

args){
Scanner reader = new reader(System.in);
System.out.println("请输入一个整数");
int n = reader.nextInt();
abs(n);
}

public static void abs(int a){
if(a>=0)
System.out.println("绝对值是"+a);
else
System.out.println("绝对值是"+(-a));
}
}

3. 在上述题目的基础上,修改abs成为带返回值的方法,即public static int abs(int a),实现相同的功能。

import java.util.Scanner;

public class Demo{
public static void main(String[] args){
Scanner reader = new reader(System.in);
System.out.println("请输入一个整数");
int n = reader.nextInt();
System.out.println("绝对值是"+abs(n));
}

public static int abs(int a){
if(a>=0)
return a;
else
return -a;
}
}

4. 定义一个方法public static void draw( int n, char ch),实现输出n个ch符号。在main方法中提示用户输入相应数据,调用draw方法输出图形。

import java.util.Scanner;

public class Multiplication {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("要显示哪个符号?");
char c = reader.next().charAt(0);
System.out.println("要显示多少个?");
int num = reader.nextInt();
draw(num,c);
}

public static void draw( int n, char ch){
for(int i=1; i<=n; i++)
System.out.print(ch);
System.out.println();
}
}

5. 求数值累加和的方法
public class App4{
static int sum (int n){
int s=0;
for (int i=1; i<=n; i++ )
s+=i;
return s;
}
public static void main(String[] s){
System.out.println(“1~10的累加和是” + sum(10));
}
}

6. 定义一个类Initial,类的内部重载initArr()方法,分别实现对整型数组、双精度型数组、字符串数组的初始化功能,数组作为方法的参数,方法体内提示用户为数组元素输入数据,然后显示所有元素。
在mian方法中创建三种类型的数组,创建Initial类的对象,分别调用initArr()方法进行初始化。

import java.util.*;

public class OverLoad2 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
Initial init = new Initial();
int a[] = new int[6];
init.initArr(a);
double b[] = new double[5];
init.initArr(b);
String s[] = new String[3];
init.initArr(s);
}
}

class Initial{
Scanner reader = new Scanner(System.in);

void initArr(int arr[]){
System.out.println("初始化整型数组");
for(int i=0;iSystem.out.println("请输入第"+(i+1)+"个整数");
arr[i] = reader.nextInt();
}
System.out.println("整型数组初始化完毕,所有元素为:");
for(int i=0;iSystem.out.print(arr[i]+" ");
System.out.println("\n-------------------------

--");
}

void initArr(double arr[]){
System.out.println("初始化双精度型数组");
for(int i=0;iSystem.out.println("请输入第"+(i+1)+"个双精度数");
arr[i] = reader.nextDouble();
}
System.out.println("双精度型数组初始化完毕,所有元素为:");
for(int i=0;iSystem.out.print(arr[i]+" ");
System.out.println("\n---------------------------");
}

void initArr(String arr[]){
System.out.println("初始化字符串型数组");
for(int i=0;iSystem.out.println("请输入第"+(i+1)+"个字符串");
arr[i] = reader.next();
}
System.out.println("字符串型数组初始化完毕,所有元素为:");
for(int i=0;iSystem.out.print(arr[i]+" ");
System.out.println("\n---------------------------");
}
}

7. 定义一个类MathDemo,类的内部重载round()方法,分别实现对单精度、双精度类型数据进行四舍五入的功能,要处理的实型数据作为参数,方法体最后将得到的结果返回。
在mian方法中定义float与double类型变量,分别赋好初值,创建MathDemo类的对象,调用round()方法,将结果显示在屏幕上。

import java.util.*;

public class OverLoad3{
public static void main(String[] args) {
// TODO Auto-generated method stub
float x = 3.475f;
double y = 3432.934;
System.out.println(x+"四舍五入后为"+MathDemo.round(x));
System.out.println(y+"四舍五入后为"+MathDemo.round(y));
}

}

class MathDemo{
static Scanner reader = new Scanner(System.in);

static int round(float a){
int n = (int)a;
if(a-n>=0.5)
return n+1;
else
return n;
}

static long round(double a){
long n = (long)a;
if(a-n>=0.5)
return n+1;
else
return n;
}
}



第5章 生命周期及作用域

1. 定义一个按身高计算标准体重的类StdWeight,其中包含两个静态的成员方法:forMale(double h)计算男子标准体重、forFemale(double h)计算女子标准体重,两个方法均带返回值。
在应用程序类的main方法中提示用户输入身高和性别,调用StdWeight类的方法得到标准体重,显示结果。
计算公式:
标准体重(男)=(身高cm-100)x0.9(kg)
标准体重(女)=(身高cm-100)x0.9(kg)-2.5(kg)
正常体重:标准体重+-(多少)10%.
提示:
控制实数保留N位小数:(如保留2位小数)
import java.text.DecimalFormat;
double num = 21.3749;
DecimalFormat df = new DecimalFormat("0.00");
String s = df.format(num); //21.37

参考代码:
import java.util.*;
import java.text.*;

public class Demo {

public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("请输入您的身高(单位厘米)");
double height = reader.nextDouble();
System.out.println("请选择您的性别:1.男 2.女");
int

sex = reader.nextInt();
DecimalFormat df = new DecimalFormat("0.00");
if(sex==1)
System.out.println("标准体重是"
+df.format(StdWeight.forFemale(height))+"公斤");
else if(sex==2)
System.out.println("标准体重是"
+df.format(StdWeight.forMale(height))+"公斤");
else
System.out.println("您输入的选择不正确。");
}

}

class StdWeight{
static double forMale(double h){
return (h-100)*0.9;
}
static double forFemale(double h){
return (h-100)*0.9-2.5;
}
}



第6章 Java常用类与函数库

1. 提示用户输入三角型两边边长与其夹角度数,利用公式s=1/2absin(c)计算三角型面积,输出结果。
注意:正弦值的计算对象是弧度制的角,需将角度转换为弧度:π/180。
import java.util.Scanner;
import java.text.DecimalFormat;

class Demo{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
System.out.println("请输入三角型两边边长");
double a = reader.nextDouble();
double b = reader.nextDouble();
System.out.println("请输入两边夹角度数");
double angle = reader.nextDouble();
double s = 0.5*a*b*Math.sin(angle*Math.PI/180);
DecimalFormat df = new DecimalFormat("0.00");
String area = df.format(s);
System.out.println("该三角型面积是"+area);
//System.out.println(Math.sin(90));

}
}

2. 编写Java应用程序,使用Vector向量来保存用户输入的若干字符串。循环读入用户输入的字符串,以end作为结束。将所有字符串显示出来。在所有字符串的中间位置插入“NICE”,再次显示所有字符串。
import java.util.Vector;
import java.util.Scanner;

class Demo{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
Vector vct = new Vector(1,1);
System.out.println("请输入字符串,以输入end作为结束");
String str;
do{
str = reader.next();
vct.add(str);
}while(!str.equals("end"));
System.out.println("您刚才输入的所有字符串是:");
System.out.println(vct.toString());
System.out.println("插入NICE到中间位置:");
int n = vct.capacity();
vct.insertElementAt("NICE",n/2);
System.out.println(vct.toString());
}

}

3. 显示InputDialog输入对话框实现对用户输入的英文单词进行简单处理(转换为大写、转换为小写、反转显示)。程序运行效果如下图:




import javax.swing.JOptionPane;

class Demo{
public static void main(String[] args){
String str = JOptionPane.showInputDialog("请输入一个英文单词");
str = str.trim();
String[] items = {"转换为大写", "转换为小写", "反转显示" };
Object selectedValue = JOptionPane.showInputDialog(null,
"请选择",
"输入",
https://www.360docs.net/doc/c64482971.html,RMATION_MESSAGE,
nul

l,
items,
items[0]);
String choice = (String)selectedValue;
if(choice.equals("转换为大写"))
JOptionPane.showMessageDialog(null,str.toUpperCase(),
"操作结果",https://www.360docs.net/doc/c64482971.html,RMATION_MESSAGE);
else if(choice.equals("转换为小写"))
JOptionPane.showMessageDialog(null,str.toLowerCase(),
"操作结果",https://www.360docs.net/doc/c64482971.html,RMATION_MESSAGE);
else
JOptionPane.showMessageDialog(null,
(new StringBuffer(str).reverse()),
"操作结果",https://www.360docs.net/doc/c64482971.html,RMATION_MESSAGE);
}
}



第7章 对象的进一步探讨--面向对象中的继承

1. 定义一个球类Ball,包含一个私有成员变量半径(double r),两个公有成员方法:设定半径值方法( void setR(double x) 、 得到半径值方法(double getR( ))。
定义一个台球类Billiards,继承Ball类,包含一个私有成员变量颜色(String color),两个公有成员方法:设定颜色方法(void setCol (String clo))、输出信息方法(void show()),其中show方法可以输出该台球的颜色和半径值。
定义一个公有类,测试前两个类。

class Ball{
private double r;
public void setR(double x){
r = x;
}
public double getR(){
return r;
}
}

class Billiards extends Ball{
private String color;
public void setCol(String col){
color = col;
}
public void show(){
System.out.println("台球的颜色是"+color+",半径是"+getR());
}
}

public class Demo{
public static void main(String[] args){
Ball b1 = new Ball();
b1.setR(10);
System.out.println("球的半径是"+b1.getR());
Billiards b2 = new Billiards();
b2.setR(5);
b2.setCol("蓝色");
b2.show();
}
}

2. 定义材料类Material,包含:
保护的成员变量名称、单价(String name; double price;)
为数据初始化赋值的构造方法;
公有的成员方法得到所有信息(public String toString())。
定义木材类Wood,继承自材料类。包含:
私有的成员变量颜色(String col;)
为数据初始化赋值的构造方法;
覆盖公有的成员方法得到所有信息(public String toString())。
定义公共类,测试上述两个类的使用。
思考:
程序中把木材类中toString()方法的public 去掉会产生什么结果?为什么?
程序中把材料类中toString()方法的public 去掉会产生什么结果?为什么?
class Material{
protected String name;
protected double price;
Material(String n,double p){
name = n;
price = p;
}
public String toString(){
return name+"的价格是"+price;
}
}

class Wood extends Material{
private String col;
Wood(String n,double p,String c){
super(n,p);
col = c;
}
public String toString(){
return name+"的价格是"+price+",颜色是"+col;
}
}
public class Demo{
public static void main(String[] args){
Material m = new Material("大理石",1000);

System.out.println(m.toString());
Wood w = new Wood("檀木",1200,"红棕");
System.out.println(w.toString());
}
}

思考题:
木材类中toString()方法的public 去掉程序会出错,因为该方法由材料类继承而来,子类覆盖父类的方法时不能缩小其访问权限,public去掉就会变成包访问权限,此处不能去掉。
材料类中toString()方法的public 去掉会产生同样的问题,因为toString方法不是材料类自定义的,是所有类的父类Object类提供的。

3. 改写例7-8,给Shape类增加构造方法,能够对颜色进行初始化设置,思考两个子类的构造方法该如何修改才能使程序正常运行。
class Demo{
public static void main(String[] args){
Circle c = new Circle("blue",1);
c.printInfo();
Rectangle rect = new Rectangle("green",3,4);
rect.printInfo();
}
}

class Shape{
String color;
Shape(String c){
color = c;
}
double getArea(){
return 0;
}
}

class Circle extends Shape{
double radius;
Circle(String c, double r){
super(c);
radius = r;
}
double getArea(){
return Math.PI*radius*radius;
}
void printInfo(){
System.out.println("圆的颜色是:"+color+"面积是"+getArea());
}
}

class Rectangle extends Shape{
double width, height;
Rectangle(String c, double w, double h){
super(c);
width = w;
height = h;
}
double getArea(){
return width*height;
}
void printInfo(){
System.out.println("矩形的颜色是:"+color+"面积是"+getArea());
}
}





第8章 深入多态
1. 要使程序运行后出现如下结果,该如何修改程序代码。

去掉Person类前面的final,去掉Student类中show()方法前面的final。
class Person {
String name;
char sex;
Person(){}
Person(String n,char s){
name = n;
sex = s;
}
void show(){
System.out.println("name is "+name+", sex is "+sex);
}
}

class Student extends Person{
int number;
Student(){}
Student(String n, char s, int num){
name = n;
sex = s;
number = num;
}
void show(){
System.out.println("name is "+name+", sex is "+sex+",number is "
+number);
}
}

class Pupil extends Student{
double hcScore;
Pupil(){}
Pupil (String n, char s, int num,double hcs){
name = n;
sex = s;
number = num;
hcScore = hcs;
}
void show(){
System.out.println("name is "+name+", sex is "+sex+",number is "
+number+",Score is "+hcScore);
}
}

public class App01{
public static void main(String[] s){
Person p = new Person("小明", '男');
p.show();
Student stu = new Student("小明", '男',101);
stu.show();
Pupil pu = new Pupil("小明", '男',101,95);
pu.show();
}
}

2. 求正方形的面积
a)创建一个接口IShape ,接口中有一个抽象方法
public double area( );
b)定义一个类square,且实现IShape接口。square类有一个属性表示正方形的边长;构造方法初始化该边

长。
c)定义一个主类,在此类中,创建square类的实例,求该正方形面积。
interface IShape{
public double area();
}
class square implements IShape{
double length ;
public square(double l){
length = l;
}
public double area(){
return length*length;
}
}
public class Test {
public static void main(String[] args) {
square s = new square(5);
System.out.println(s.area());
}
}

第9章 使用异常处理

1. 查阅API文档,选择一个比较了解的Java系统异常,例如ArrayIndexOutofBoundsException(数组越界异常),编程创建并抛出这个异常的实例。运行这个程序并观察执行结果。
可参考本章例题。

2. 询问用户是哪个年级的同学,对输入的数据进行保存,将结果显示在屏幕上。要求合法年级为1、2、3,自定义异常类GradeException,对输入非法的情况进行异常处理。
不同情况下程序运行结果:

你是几年级同学?
3
你是3年级的同学~!

import java.util.Scanner;
class GradeException extends Exception{
GradeException(String msg){
super(msg);
}
}
public class Demo{
static void grade(int g) throws GradeException{
if(g!=1&&g!=2&&g!=3){
GradeException e=new GradeException("输入了不存在的年级!");
throw e;
}
else
System.out.println("你是"+g+"年级的同学~!");
}

public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("你是几年级同学?");
int input= reader.nextInt();
try{
grade(input);
}
catch(GradeException e){
System.out.println(e.getMessage());
}
}
}

第10章 基于Swing的图形界面编程

1. 编写程序,实现如下效果:

import javax.swing.*;
import java.awt.*;

public class GUIDemo {

public static void main(String[] args) {
JFrame frm = new JFrame("My First Frame");
frm.setSize(300,300);
frm.setLocationRelativeTo(null);

JPanel contentPane=new JPanel( );
frm.setContentPane(contentPane);
Color c = new Color(170,255,150);
contentPane.setBackground(c);

Icon icon = new ImageIcon("China.png");
JButton btn = new JButton("中国",icon);
btn.setBackground(Color.YELLOW);
btn.setForeground(Color.BLUE);
Font font = new Font("华文行楷",Font.BOLD,48);
btn.setFont(font);
contentPane.add(btn);

frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frm.setVisible( true );
}
}

2. 用标签实现如下效果:


//MyFrame.java
import javax.swing.*;
import java.awt.*;

public class MyFrame extends JFrame {
MyFrame(String s){
super(s);
setSize(300,300);
setLocationRelativeTo(null);

JPanel contentPane=new JPanel( );
setContentPane(contentPane);
contentPane.setBackground(Color.BLACK);

Icon icon = new ImageIcon("images.jpeg");
JLabel lab1 = new JLabel(icon);
icon = new ImageIcon("Chi

na.png");
JLabel lab2 = new JLabel(icon);
JLabel lab3 = new JLabel("天 佑 中 华");
Font font = new Font("华文行楷",Font.BOLD,48);
lab3.setFont(font);
lab3.setForeground(Color.YELLOW);
contentPane.add(lab1);
contentPane.add(lab2);
contentPane.add(lab3);

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible( true );
}
}

//GUIDemo.java
public class GUIDemo {
public static void main(String[] args) {
MyFrame frm = new MyFrame("祈祷~~");
}
}

3. 编写程序,完成以下界面的设计和显示:



//GUIDemo.java
public class GUIDemo {

public static void main(String[] args) {
MyFrame frm = new MyFrame("注册界面");
}

}

//MyFrame.java
import javax.swing.*;
import java.awt.*;

public class MyFrame extends JFrame {

private JComboBox cmbMonth;
private JLabel labID,labPW,labPW2,labResume,labSex,labCardType,labCardID,labAgree;
private JTextField txfID,txfCard;
private JPasswordField pwf1,pwf2;
private JTextArea txaResume;
private JRadioButton rdbMale,rdbFemale;
private ButtonGroup grp;
private JComboBox cmbCard;
private JCheckBox chkAgree;

MyFrame(String s){
super(s);
setSize(320,400);
setLocationRelativeTo(null);

JPanel contentPane=new JPanel( );
setContentPane(contentPane);

labID = new JLabel("用 户 名:");
txfID = new JTextField(20);
labPW = new JLabel("密 码:");
pwf1 = new JPasswordField(20);
pwf1.setEchoChar('*');
labPW2 = new JLabel("确认密码:");
pwf2 = new JPasswordField(20);
pwf2.setEchoChar('*');
labResume = new JLabel("个人简介:");
txaResume = new JTextArea(10,20);
labSex = new JLabel("性 别:");

rdbMale = new JRadioButton("男");
rdbFemale = new JRadioButton("女");
grp = new ButtonGroup();
grp.add(rdbMale);
grp.add(rdbFemale);

labCardType = new JLabel("证件类型:");
String cardType[] = {"身份证","护照","学生证","驾驶证","军官证","其他"};
cmbCard = new JComboBox(cardType);

labCardID = new JLabel("证件号码:");
txfCard = new JTextField(20);

labAgree = new JLabel("同意服务条款:");
chkAgree = new JCheckBox("我已经看过并同意使用协议");

contentPane.add(labID);
contentPane.add(txfID);
contentPane.add(labPW);
contentPane.add(pwf1);
contentPane.add(labPW2);
contentPane.add(pwf2);
contentPane.add(labResume);
contentPane.add(txaResume);
contentPane.add(labSex);
contentPane.add(rdbMale);
contentPane.add(rdbFemale);
contentPane.add(labCardType);
contentPane.add(cmbCard);
contentPane.add(labCardID);
contentPane.add(txfCard);
contentPane.add(labAgree);
contentPane.add(chkAgree);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible( true );
}
}

4. 完成下图所示的界面设计并显示出来:

// MenuFrame.java
import javax.swing.*;

public cla

ss MenuFrame extends JFrame {
private JMenuBar menuBar;
private JMenu fileMenu,subopenMenu,editMenu,supoptionMenu;
private JMenuItem newItem,saveItem,exitItem,copyItem,pasteItem;
private JMenuItem docItem,pptItem,xlsItem;
private JCheckBoxMenuItem linewrapItem;
private JRadioButtonMenuItem fullItem,normalItem;

MenuFrame(String s){
super(s);
setSize(200,300);
this.setLocationRelativeTo(null);

menuBar = new JMenuBar(); //菜单条
setJMenuBar(menuBar);

fileMenu = new JMenu("文件"); //"文件"菜单
newItem = new JMenuItem("新建");
saveItem = new JMenuItem("保存");
exitItem = new JMenuItem("退出");

subopenMenu = new JMenu("打开"); //"打开"子菜单
Icon icon = new ImageIcon("icon_doc.gif");
docItem = new JMenuItem("word文档",icon);
icon = new ImageIcon("icon_ppt.gif");
pptItem = new JMenuItem("ppt幻灯片",icon);
icon = new ImageIcon("icon_xls.gif");
xlsItem = new JMenuItem("xls表格",icon);
subopenMenu.add(docItem);
subopenMenu.add(pptItem);
subopenMenu.add(xlsItem);

fileMenu.add(newItem); //"文件"菜单组合
fileMenu.add(subopenMenu);
fileMenu.add(saveItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);

editMenu = new JMenu("编辑"); //"编辑"菜单
copyItem = new JMenuItem("复制");
pasteItem = new JMenuItem("粘贴");

supoptionMenu = new JMenu("选项"); //"选项"子菜单
linewrapItem = new JCheckBoxMenuItem("自动换行");
fullItem = new JRadioButtonMenuItem("全屏显示");
normalItem = new JRadioButtonMenuItem("正常显示");
ButtonGroup grp = new ButtonGroup();
grp.add(fullItem);
grp.add(normalItem);
supoptionMenu.add(linewrapItem);
supoptionMenu.addSeparator();
supoptionMenu.add(fullItem);
supoptionMenu.add(normalItem);

editMenu.add(copyItem); //"编辑"菜单组合
editMenu.add(pasteItem);
editMenu.addSeparator();
editMenu.add(supoptionMenu);

menuBar.add(fileMenu); //菜单放置到菜单条
menuBar.add(editMenu);

this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible( true );
}

}

//GUIDemo.java
public class Demo{

public static void main(String[] args) {
MenuFrame frm = new MenuFrame("菜单演示");
}

}

5. 把面板和布局管理配合在一起使用,实现显示如下界面:
运行后试着调整窗体的尺寸,观察窗体内组件的变化。

//GUIDemo.java
public class GUIDemo {

public static void main(String[] args) {
MyFrame frm = new MyFrame("计算器");
}

}

// MyFrame.java
import javax.swing.*;
import java.awt.*;

public class MyFrame extends JFrame {

JTextField txfResult = new JTextField();

MyFrame(String s){
super(s);
setSize(250,200);
setLocationRelativeTo(null);

JPanel contentPane=new JPanel( );
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());

PanNumber pa

n = new PanNumber();

contentPane.add(txfResult,BorderLayout.NORTH);
contentPane.add(pan);


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible( true );
}

}

// PanNumber.java
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.GridLayout;

public class PanNumber extends JPanel {
PanNumber(){
setLayout(new GridLayout(4,4));
addButton("7");
addButton("8");
addButton("9");
addButton("/");
addButton("4");
addButton("5");
addButton("6");
addButton("*");
addButton("1");
addButton("2");
addButton("3");
addButton("-");
addButton("0");
addButton(".");
addButton("=");
addButton("+");
}
void addButton(String s){
JButton btn = new JButton(s);
add(btn);
}

}



第11章 可视化程序的事件处理

1. 编写程序,能够在窗体内显示被点击按钮的信息。运行效果图如下:

// MyFrame.java
import javax.swing.*;
import java.awt.event.*;

public class MyFrame extends JFrame implements ActionListener{

JButton btnOK,btnCancel; JLabel lab;

MyFrame(String s){

super(s);
setSize(200,200);
setLocationRelativeTo(null);

JPanel pan = new JPanel();
setContentPane(pan);

btnOK = new JButton("OK");
btnOK.addActionListener(this);
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(this);
lab = new JLabel(" ");

pan.add(btnOK);
pan.add(btnCancel);
pan.add(lab);

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setVisible( true );
}

public void actionPerformed(ActionEvent e){
if(e.getSource()==btnOK)
lab.setText("点击了确定按钮");
if(e.getActionCommand() .equals("Cancel"))
lab.setText("点击了取消按钮");
}
}

// EventDemo.java
public class EventDemo {
public static void main(String[] args) {
MyFrame frm = new MyFrame("按钮事件演示");
}
}

2. 编写程序,实现如下界面,当用户在文本框中输入内容后,点击不同的按钮,能够把文本框中的内容粘贴到文本区中。“重置”按钮实现将文本框和文本区中的内容清空。界面上的文本区只能显示内容,不能让用户输入文本。
提示:
得到文本框中的文本、得到选中的文本、设置文本区中的文本、附加文本等,设置文本区不可用等,JTextField和JTextArea类均有相应方法实现。

//MyFrame.java
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class MyFrame extends JFrame implements ActionListener{

JButton btnPasteAll,btnPasteSeleted,btnAppendAll,btnAppendSeleted,
btnReset;
JTextField txt ;
JTextArea txa;
JPanel pan = new JPanel();
MyFrame(String s){
super(s);
setSize(250,300);
this.setLocationRelativeTo(null);
setContentPane(pan);

txt = new JTextField(20);
txa = new JTextArea(5,20);
txa.setEnabled(false); //txa.setEditable(false);

btnPast

eAll = new JButton("粘贴全部");
btnPasteSeleted = new JButton("粘贴所选");
btnAppendAll = new JButton("附加全部");
btnAppendSeleted = new JButton("附加所选");
btnReset = new JButton("重置");
btnPasteAll.addActionListener(this);
btnPasteSeleted.addActionListener(this);
btnAppendAll.addActionListener(this);
btnAppendSeleted.addActionListener(this);
btnReset.addActionListener(this);

pan.add(txt);
pan.add(txa);
pan.add(this.btnPasteAll);
pan.add(this.btnPasteSeleted);
pan.add(this.btnAppendAll);
pan.add(this.btnAppendSeleted);
pan.add(this.btnReset);

this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible( true );
}

public void actionPerformed(ActionEvent e){
if(e.getSource()==this.btnPasteAll)
txa.setText(txt.getText());
if(e.getSource()==this.btnPasteSeleted)
txa.setText(txt.getSelectedText());
if(e.getSource()==this.btnAppendAll)
txa.append(txt.getText());
if(e.getSource()==this.btnAppendSeleted)
txa.append(txt.getSelectedText());
if(e.getSource()==this.btnReset){
txt.setText("");
txa.setText("");
}
}
}

//EventDemo.java
public class EventDemo {
public static void main(String[] args) {
MyFrame frm = new MyFrame("按钮事件演示");
}
}

3. 模仿例题,实现在窗体内移动鼠标时,能够实时显示鼠标指针的坐标位置。

// MouseFrame.java
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.*;

public class MouseFrame extends JFrame implements MouseMotionListener {
JPanel pan;
JLabel lab;
MouseFrame(String s){
super(s);
setSize(200,200);
setLocationRelativeTo(null);
pan = new JPanel();
setContentPane(pan);

lab = new JLabel();
pan.add(lab);
addMouseMotionListener(this);

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible( true );
}

public void mouseDragged(MouseEvent e) { }

public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
String s = "("+x+","+y+")";
lab.setText(s);
lab.setBounds(x,y,50,20);
}
}

// EventDemo.java
public class EventDemo {
public static void main(String[] args) {
MouseFrame frm = new MouseFrame("鼠标事件演示");
}
}

4. 参考例题,编写程序,给界面上的文本框增加键盘事件处理,当在文本框中输入内容时,界面上不可编辑的文本区显示相应的按键信息。
实现原理:在键盘事件接口的三个方法中均得到按键码,再根据按键码转换为按键信息,增加到文本区中显示。
e.getKeyText(e.getKeyCode())
提示:最好使用带滚动窗格的文本区。输出按键信息的同时还输出方法名称,以方便观察按键事件处理的先后顺序。

//KeyEventFrame .java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.BorderLayout;
import javax.swing.*;;

publ

ic class KeyEventFrame extends JFrame implements KeyListener {

JTextField txt;
JTextArea txa;
JScrollPane scroll;
JPanel pan;
KeyEventFrame(String s){
super(s);
setSize(500,300);
setLocationRelativeTo(null);

txt = new JTextField();
txa = new JTextArea();
txa.setEditable(false);
scroll = new JScrollPane(txa);

pan = new JPanel();
pan.setLayout(new BorderLayout());
pan.add(txt,BorderLayout.NORTH);
pan.add(scroll,BorderLayout.CENTER);

setContentPane(pan);

txt.addKeyListener(this);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible( true );
}

public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
txa.append("keyTyped: "+ e.getKeyChar() +"\n");
}

public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
txa.append("keyPressed: "+e.getKeyText(e.getKeyCode())+"\n");
}

public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
txa.append("keyReleased: "+e.getKeyText(e.getKeyCode())+"\n");
}

}

// EventDemo.java
public class EventDemo {
public static void main(String[] args) {
KeyEventFrame frm = new KeyEventFrame("键盘事件演示");
}
}

5. 编写程序,实现使用键盘上的上下左右箭头控制界面上图片的移动。移动到边界时从界面另一侧出现。移动过程中显示另一个图片,停止时恢复原来的图片。



// KeyEventFrame.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.*;

public class KeyEventFrame extends JFrame implements KeyListener {
JPanel pan;
JLabel lab;
Icon icon1 = new ImageIcon("01.gif");
Icon icon2 = new ImageIcon("02.gif");
int x,y;
KeyEventFrame(String s){
super(s);
this.setSize(400,300);
this.setLocationRelativeTo(null);
pan = new JPanel();
this.setContentPane(pan);

pan.setLayout(null);
lab = new JLabel(icon1);

x = (this.getWidth()-50)/2;
y = (this.getHeight()-50)/2;
lab.setBounds(x,y,50,50);

pan.add(lab);

this.addKeyListener(this);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub

}

public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int keycode = e.getKeyCode();
if(keycode == KeyEvent.VK_UP)
y = y<=-50?this.getHeight()-50:y-5;
if(keycode == KeyEvent.VK_DOWN)
y = y>=this.getHeight()?0:y+5;
if(keycode == KeyEvent.VK_LEFT)
x = x<=-50?this.getWidth()-50:x-5;
if(keycode == KeyEvent.VK_RIGHT)
x = x>=this.getWidth()?0:x+5;
lab.setIcon(icon2);
lab.setBounds(x,y,50,50);
}

public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
lab.setIcon(icon1);
}

}

// GUIDemo.java
publ

ic class GUIDemo {
public static void main(String[] args) {
KeyEventFrame frm = new KeyEventFrame("键盘事件演示");
}
}

6. 编写程序,在界面上放置若干按钮,面板使用网格布局,要求有15像素的水平垂直间隔。使用弹出式菜单,点击菜单项时弹出颜色对话框,对相应的控件进行背景色设置。
提示:
需要给框架、按钮响应鼠标按下事件处理;
需要给菜单项响应点击事件处理;
弹出式菜单JPopupMenu。创建时通常不给参数,大多由单击鼠标右键触发。
使用add()方法给弹出式菜单添加菜单项。
在mouseReleased()方法中通过e.isPopupTrigger()方法判断是否右键按下触发弹出式菜单。使用public void show(Component c, int x, int y)方法显示菜单。如:
public void mouseReleased(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if(e.isPopupTrigger())
popup.show(this,x,y);

}









// MyFrame.java
import javax.swing.*;
import java.awt.event.*;
import java.awt.GridLayout;
import java.awt.Color;

public class MyFrame extends JFrame
implements ActionListener,MouseListener{
JPanel pan;
JPopupMenu popup;
JMenuItem colorItem;
JButton[] btn;
Object source;

public MyFrame(String s) {
super(s);
this.setSize(400,300);
this.setLocationRelativeTo(null);
pan = new JPanel(new GridLayout(3,3,15,15));
this.setContentPane(pan);

btn = new JButton[9];
for(int i=0;i<9;i++){
btn[i] = new JButton("" + (i+1) );
btn[i].addMouseListener(this);
pan.add(btn[i]);
}

popup = new JPopupMenu();
colorItem = new JMenuItem("颜色设置");
popup.add(colorItem);

colorItem.addActionListener(this);
this.addMouseListener(this);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}

public void mouseClicked(MouseEvent e) { }

public void mousePressed(MouseEvent e) { }

public void mouseReleased(MouseEvent e) {
int x = e.getX();
int y = e.getY();
source = e.getSource();
if(source.getClass().getName().equals("javax.swing.JButton")){
x = x+(int)((JButton)e.getSource()).getLocation().getX();
y = y+(int)((JButton)e.getSource()).getLocation().getY();
}
if(e.isPopupTrigger())
popup.show(this,x,y);
}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void actionPerformed(ActionEvent e){
JColorChooser chooser = new JColorChooser();
Color color = chooser.showDialog(null,"调色板",Color.WHITE);
if(color != null ){
if( source.getClass().getName().equals("javax.swing.JButton"))

((JButton)source).setBackground(color);
else
pan.setBackground(color);
}
}
}

// GUIDemo.java
public class GUIDemo {
public static void main(String[] args) {
MyFrame frm = new MyFrame("文件对话框演示");
}
}




第12章 Java多线程机制

1. 使用Thread类的子类实现线程,其功能为循环输出0-9数字,每次随机休眠不到10毫秒的时间。在main()方法中创建两个这样的线程,启动运行。所有线程开始、结束都要有相应的文字描述。
// TestMitiThread.java
public class TestMitiThread {
public static void main(String[] rags) {
System.out.println("main线程运行开始!");
new MitiSay("A").start();
new MitiSay("B").start();
System.out.println("main线程运行结束!");
}
}

class MitiSay extends Thread {
public MitiSay(String threadName) {
super(threadName);
}
public void run() {
System.out.println(getName() + " 线程运行开始!");
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName() + " 线程运行结束!");
}
}

2. 使用Runnable接口实现线程,完成与上题同样的功能。
public class TestMitiThread1 implements Runnable {

public static void main(String[] args) {
System.out.println("main线程运行开始!");
TestMitiThread1 test = new TestMitiThread1();
Thread thread1 = new Thread(test);
Thread thread2 = new Thread(test);
thread1.start();
thread2.start();
System.out.println("main线程运行结束!");
}

public void run() {
System.out.println(Thread.currentThread().getName()
+ " 线程运行开始!");
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + Thread.currentThread().getName());
try {
Thread.sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()
+ " 线程运行结束!");
}
}


相关文档
最新文档