皮德常java课后答案修正版

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

角谷猜想:任何一个正整数n,如果它是偶数则除以2,如果是奇数则乘以3加上1,
这样得到一个新的整数,如继续进行上述处理,则最后得到的数一定是1。

编写应用程序和小程序程序分别证明:所有的3至10000的数都符合上述规则。

应用程序如下:
public class Jiaogu{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
int x,n,i;
for(x=3;x<=10000;x++)
{ n=x;
while(n!=1)
if(n%2==0)
n=n/2;
else
n=n*3+1;
System.out.println(x+" 符合角谷猜想!");
}
}
}
小程序如下:
package javaapplication2;
import java.awt.Graphics;
import java.util.*;
import java.applet.Applet;
public class JavaApplication2 extends Applet
{
public void paint(Graphics g)
{
int x,n,i=10;
for(x=3;x<=10000;x++)
{
n=x;
while(n!=1)
if(n%2==0)
n=n/2;
else
n=n*3+1;
g.drawString (x+" 符合角谷猜想!",25,25+i);
i=i+15;
}
}
}
第2 章习题5
2、编写一个小程序(Applet),要求输入两个整数,在状态条显示较大的数,紧跟着显示“is larger”。

若二者相等,显示“the two numbers are equal!”。

程序如下:
package javaapplication3;
import java.applet.*;
import java.awt.*;
public class JavaApplication3 extends Applet{
Label lab1,lab2;
TextField input1,input2;
int one,two;
public void init(){
lab1=new Label ("输入第一个整数");
lab2=new Label ("输入第二个整数");
input1=new TextField (6);
input2=new TextField(6);
add(lab1);
add(input1);
add(lab2);
add(input2);
}
public boolean action(Event e,Object o)
{
int max;
if(e.target == input1 || e.target == input2 )
{
one=Integer.parseInt (input1.getText ());
two=Integer.parseInt (input2.getText ());
if(one==two)
showStatus("the two numbers are equal!");
else{
max=(one>two)?one:two;
showStatus(max+" is larger");
}
}
return true;
}
}
3、编写一个程序模拟同时掷两个骰子。

程序要用Math.random( )模拟产生第一个骰子,然后再产生第二个骰子,将两个结果相加。

相加的和等于7的可能性最大,等于2和12的可能性最小。

下图表示了出现36种情况的组合。

程序模拟掷3600次骰子,判断求和结果是否合理,共有6种情况的和是7,故在3600次掷骰子的结果中应当有1/6的可能性是7。

程序如下:
package touzi;
/**
*
* @author Administrator
*/
public class Touzi
{
public static void main(String[] args)
{
double result2; double result7; double result12;
int n1, n2;
int times2 = 0;
int times7 = 0;
int times12 = 0;
for (int i = 0; i < 3600; i++)
{
n1 = (int) (Math.random() * 6 + 1 );
n2 = (int) (Math.random() * 6 + 1 );
if ((n1 + n2) == 2)
times2++;
else if ((n1 + n2) == 7)
times7++;
else if ((n1 + n2) == 12)
times12++;
}
result2 = times2/3600.0;
result7 = times7/ 3600.0;
result12 = times12/3600.0;
System.out.println("和为 2 的次数 : "+times2+" 比率 : " + result2);
System.out.println("和为 7 的次数 : "+times7+" 比率 : " + result7);
System.out.println("和为 12 的次数 : "+times12+" 比率 : " + result12); }
}
运行结果:
run:
和为 2 的次数 : 83 比率 : 0.023055555555555555
和为 7 的次数 : 552 比率 : 0.15333333333333332
和为 12 的次数 : 105 比率 : 0.029166666666666667
成功构建 (总时间: 1 秒)
第3 章习题1
编程:编写一个applet,要求输入一个任意长度的整数(long类型变量所允许的范围内),将这个数分成独立的数字,并分开显示。

例如输入32439则显示3 2 4 3 9。

程序如下:
package fenkai;
/**
*
* @author Administrator
*/
import java.applet.*;
import java.awt.*;
public class Fenkai extends Applet{ String str;
TextField input;
Label Linput;
public void init(){
Linput=new Label("输入一个整数"); input=new TextField(10);
add(Linput);
add(input);
}
public boolean action(Event e,Object o){ if(e.target==input){
s tr=input.getText();
}
r epaint();
r eturn true;
}
p ublic void paint(Graphics g){
f or(int i=0;i<str.length();i++)
g.drawString(str.charAt(i)+"",50+i*10,50); }
}
编程:计算从0 到10的平方和立方值。

并以如下格式显示:数平方立方
000
111
248
3927
…………………………………
101001000
程序如下:
package pingfanglifang;
/**
*
* @author Administrator
*/
import java.applet.*;
import java.awt.*;
public class Pingfanglifang extends Applet{
public void paint(Graphics g){
g.drawString("整数",20,15);
g.drawString("平方",80,15);
g.drawString("立方",140,15);
f or(int i=0;i<=10;i++){
g.drawString(""+i,20,30+i*20);
g.drawString(""+i*i,80,30+i*20);
g.drawString(""+i*i*i,140,30+i*20);
}
}
}
第3 章习题3 采用循环语句打印如下图形。

* *
** **
*** ***
**** ****
***** *****
// 程序清单
/*
* graph1.java
*/
public class graph1 {
// draw n stars
static void star(int n) {
f or (int i = 1; i <= n; i++) {
System.out.print("*");
}
}
// draw n spaces
static void space(int n) {
f or (int i = 1; i <= n; i++) {
System.out.print(" ");
}
}
public static void main(String[] args) {
// the length of space
int i = 20; // the
length of star int j = 1;
for (j = 1; j <= 5; j++) {
star(j);
s pace(i); star(j);
i -= 2;
System.out.println();
}
}
}
第3 章习题4
编程:读取一个矩形的边长,然后输出一个空心矩形。

例如读入边长5,应当输出:
** * * *
**
**
**
** * * *
// 程序清单
/* 采用小程序实现
*graph2.java
*/
public class graph2 extends Applet{
int num;
TextField input;
Label Linput;
public void init(){
Linput=new Label("Enter an integer:");
input=new TextField(10); add(Linput);
add(input);
}
public boolean action(Event e,Object o){
if(e.target==input)
num=Integer.parseInt(input.getText());
repaint();
r eturn true;
}
public void paint(Graphics g)
{
int i,j;
for(i=0;i<num;i++)
if(i==0||i==num-1)
for(j=0;j<num;j++)
g.drawString ("*",30+10*j,50+10*i);
else{
g.drawString ("*",30,50+10*i);
g.drawString ("*",30+10*(num-1),50+10*i);
}
}
}
/* 采用应用程序实现
* graph2_1.java
*/
public class graph2_1 {
private int number;
public NO_2_4(int number) {
t his.number = number; draw(number);
}
// draw square public void
draw(int n) { if (n == 1)
System.out.println("*");
e lse { stars(n);
System.out.println();
for (int i = 0; i < n; i++) {
stars(1); space(n -
2); stars(1);
System.out.println();
}
stars(n);
System.out.println();
}
}
// draw stars
static void stars(int n) { f or (int
i = 1; i <= n; i++) {
System.out.print("*");
}
}
// draw spaces
static void space(int n) {
for (int i = 1; i <= n; i++) {
System.out.print(" ");
}
}
public static void main(String[] args) {
g raph2_1 temp = new graph2_1(7);
}
}
第3 章习题5
编程:编写一个applet,输入一个数,判断输入的这个数是否为回文数。

所谓回文数就是从左向右看和从右向左看都一样。

例如:121、13431都是回文数,而12345不是回文数。

程序如下:
package huiwen;
/**
*
* @author Administrator
*/
import java.awt.*;
import java.applet.*;
public class Huiwen extends Applet{
TextField input;
Label message;
boolean b;
p ublic void init(){
message=new Label("输入一个数:");
input=new TextField(10);
add(message);
add(input);
}
public boolean action(Event e,Object o){
String str;
b=true;
if(e.target==input){
str=input.getText();
for(int i=0,j=str.length()-1;i<j;i++,j--)
if(str.charAt(i)!=str.charAt(j))
b=false;
}
repaint();
return true;
}
public void paint(Graphics g){
if( b )
g.drawString(input.getT ext()+"是回文数",50,100);
else
g.drawString(input.getT ext()+"不是回文数",50,100);
}
}
编写一个applet,采用下列公式计算e^x的值:e^x=1+(x^1)/1!+ (x^2)/2!+…+(x^n)/n!。

从键盘输入x和n,编程计算e^x的值。

程序如下:
package jisuanex;
/**
*
* @author Administrator
*/
import java.awt.*;
import java.applet.*;
public class Jisuanex extends Applet{
double result;
int x,n;
Label express1=new Label("e的");
TextField field1=new TextField(5);
Label express2=new Label("次方:");
Label express3=new Label("输入n:"); TextField field2=new TextField(5);
public void init(){
add(express1);
add(field1);
add(express2);
add(express3);
add(field2);
}
int factor(int m){
int t=1;
for(int i=1;i<=m;i++)
t=t*i;
r eturn t;
}
int f(int x , int m){
int t=1;
for(int i=1;i<=m;i++)
t=t*x;
r eturn t;
}
public boolean action(Event e,Object o){
double temp=1;
result=1;
x=Integer.parseInt(field1.getText()); n=Integer.parseInt(field2.getText());
for(int m=1;m<=n;m++)
{
temp=(double)f(x,m) / factor(m);
result += temp;
}
showStatus("结果:"+result);
repaint();
return true;
}
}
编程:产生20个int类型的随机数,针对每个数使用if-then-else判断它是大于、小于或等于下一个数(注意:最后一个数不比较)。

程序如下:
package bijiao;
/**
*
* @author Administrator
*/
public class Bijiao {
public static void main(String[] args) {
int array[] = new int[20];
for (int i = 0; i < 20; i++) {
array[i] = ((int) (Math.random() * 10e6)) % 100;
System.out.print(array[i]+" ");
}
System.out.println();
for (int i = 0; i < 19; i++) {
if (array[i] > array[i + 1])
System.out.println("第 "+ i+ " 个数("+ array[i]+ ") 大于第 "+ (i + 1)+ " 个数("+ array[i + 1]+ ")");
else if (array[i] < array[i + 1])
System.out.println("第 "+ i+ " 个数("+ array[i]+ ") 小于第 "+ (i + 1)+ " 个数("+ array[i + 1]+ ")");
else
System.out.println("第 "+ i+ " 个数("+ array[i]+ ") 等于第 "+ (i + 1)+ " 个数("+ array[i + 1]+ ")");
}
}
}
定义一个类,它包含了一个 int 类型的变量 x、若干个构造函数(根据用户自己的需要)和一个输出方法 show( )。

编程:从键盘输入一个两位以上的数,将这个数传递给这个类的变量x,采用方法 show( )逆序输出这个数。

程序如下:
package reversenum;
/**
*
* @author Administrator
*/
public class Reversenum {
private int x;
Reversenum (int x){
this.x = x;
}
public void show() {
String str;
str = Integer.toString(x);
char array[] = new char[str.length()];
array = str.toCharArray();
for(int i = str.length()-1; i >= 0;i--)
System.out.print(array[i]);
}
public static void main(String[] args) {
Reversenum temp = new Reversenum(325425);
temp.show();
}
}
2、定义一个复数类complex,它的内部具有两个实例变量:realPart 和 imagPart,分别代表复数的实部和虚部,编程实现要求的数学运算。

(1)实现两个复数相加。

复数加运算的原则是:复数的实部和虚部分别相加。

(2)实现两个复数相减。

复数减运算的原则是:复数的实部和虚部分别相减。

(3)输出运算结果,判断是否正确。

程序如下:
package complex;
/**
*
* @author Administrator
*/
public class Complex
{
private double realPart;
private double imagePart;
public Complex()
{
this.realPart = 0.0;
this.imagePart = 0.0;
}
public Complex(double real, double image)
{
this.realPart = real;
this.imagePart = image;
}
public void show()
{
if ((this.realPart == 0.0) && (this.imagePart == 0.0))
System.out.println("0");
else if (this.realPart == 0.0)
System.out.println(this.imagePart + "i");
else if (this.imagePart == 0.0)
System.out.println(this.realPart);
else
System.out.println(this.realPart + "+" + this.imagePart + "i");
}
public void add(Complex x, Complex y) {
this.realPart = x.realPart + y.realPart;
this.imagePart = x.imagePart + y.imagePart;
}
public void sub(Complex x, Complex y) {
this.realPart = x.realPart - y.realPart;
this.imagePart = x.imagePart - y.imagePart;
}
public static void main(String arg[]) {
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(2, 2);
Complex c3 = new Complex();
c1.show();
c2.show();
c3.add(c1, c2);
System.out.print("add : ");
c3.show();
c3.sub(c1, c2);
System.out.print("sub : ");
c3.show();
}
}
3、定义一个圆类 circle,它有一个变量 radius(半径)。

从键盘输出数据,通过构造函数的参数传递给 radius,编程计算并输出圆的周长和面积。

但是,你必须确保输入的数据不为负数。

程序如下:
package Circle;
import java.awt.*; import java.applet.*;
public class Circle extends Applet{
TextField banjing;
int r=0;
round Circle;
public void init(){
Label prompt;
Circle=new round();
prompt = new Label("半径:");
banjing=new TextField(20);
add( prompt );
add( banjing );
}
public void paint(Graphics g){
Circle.setRound(r);
g.drawString("面积:"+Circle.area() ,50,80);
g.drawString("周长:"+Circle.lengthCircle() ,50,100);
}
public boolean action(Event e,Object o)
{
if (e.target == banjing)
{
r = Integer.parseInt( banjing.getText() );
if(r<0)
{
showStatus("半径不能为负数!请重新输入数据。

");
return false;
}
repaint();
}
return true;
}
}
class round{
final float PI=3.14f;
int r;
void setRound(int t){
r=t;
}
float area(){
return PI*r*r;
}
float lengthCircle(){
return 2*PI*r;
}
}
4、定义一个日期类 date,确保具有如下功能:
(1)输出日期的格式具有如下几种:
YYYY MM DD
MM DD YYYY
DD MM YYYY
(2)采用重载构造函数,以上述日期格式数据为参数,创建 date 类型的对象。

程序如下:
package date;
/**
*
* @author Administrator
*/
public class Date {
int YYYY;
int MM;
int DD;
public Date(int y, int m, int d)
{
this.YYYY = y;
this.MM = m;
this.DD = d;
}
public Date( )
{
this.YYYY = 0;
this.MM = 0;
this.DD = 0;
}
public boolean isValid() {
return ( this.YYYY > 0&& this.MM > 0 && this.DD > 0 && this.MM < 13 && this.DD < 32);
}
public void showYMD() {
System.out.println(this.YYYY+" "+this.MM+" "+this.DD);
}
public void showMDY() {
System.out.println(this.MM+" "+this.DD+" "+this.YYYY);
}
public void showDMY() {
System.out.println(this.DD+" "+this.MM+" "+this.YYYY);
}
public static void main(String args[]){
Date day1=new Date();
Date day2=new Date(2003,12,1);
if(day1.isValid()){
d ay1.showYMD();
day1.showMDY();
day1.showDMY();
}
if(day2.isValid()){
day2.showYMD();
day2.showMDY();
day2.showDMY();
}
}
}
定义一个整形集合类integerSet。

这种类型的对象可以存储10 个20 至80 之间的整数,即它的内部有一个整形数组存储数据。

编程:
(1)判断两个integerSet 类对象S1 和S2 是否相等。

提示:集合相等的前提是所有元素相
等。

(2)输出两个集合对象的交集。

(3)输出两个集合对象的并集。

(4)将一个整形数据插入到一个集合对象中。

(5)从一个集合中删除某一个元素。

// 程序清单
/*
* IntegerSet.java
*
*/
public class IntegerSet {
private boolean isEmpty; //
the size of the set private final int
size = 10; // how many
elements in the set private int
current;
// set to store datas private int
set[] = new int[size];
public IntegerSet() {
// 也可以采用随机数初始化数组
// gen random ints to set[] <100
// for(int i = 0; i < size; i++)
// set[i] = ((int)(Math.random()*10e5))%100;
this.isEmpty = true;
this.current = 0; for (int i
= 0; i < size; i++)
this.set[i] = 0;
}
//clear IntegerSet
p ublic void Clear() {
t his.isEmpty = true;
t his.current = 0;
for (int i = 0; i < this.size; i++)
this.set[i] = 0;
}
// Merge two IntegerSets
public boolean MergeIntegerSets(IntegerSet arg1, IntegerSet arg2) {
// System.out.println("merge");
// argments IntegerSet is empty if
(arg1.isEmpty && arg2.isEmpty) {
t his.Clear(); return true;
}
// arg1 is empty if
(arg1.isEmpty == true) {
t his.isEmpty = false;
t his.current = arg2.current; for
(int i = 0; i < this.size; i++)
t his.set[i] = arg2.set[i]; return
true;
}
// arg2 is empty if
(arg2.isEmpty == true) {
t his.isEmpty = false;
t his.current = arg1.current; for
(int i = 0; i < this.size; i++)
t his.set[i] = arg1.set[i]; return true;
}
// arg1 equals qrg2 if
(arg1.equal(arg2) == true) {
this.isEmpty = false;
this.current = arg1.current;
for (int i = 0; i < this.size; i++)
this.set[i] = arg1.set[i];
return true;
}
// make a clone of this
IntegerSet tmp = new
IntegerSet(); tmp.isEmpty = false;
tmp.current = this.current;
for (int i = 0; i < this.size; i++)
t mp.set[i] = this.set[i];
// fill this with arg1
t his.isEmpty = false;
t his.current = arg1.current; for
(int i = 0; i < this.size; i++)
t his.set[i] = arg1.set[i];
// now merging!
for (int i = 0; i < arg2.size; i++) {
// arg2.set[i] is not in this.Set
i f (this.isIn(arg2.set[i]) == false) {
if (this.current == 10) {
System.out.println("IntegerSet Over flow!");
// restore this
t his.isEmpty = false;
t his.current = tmp.current; for
(int j = 0; j < this.size; j++)
t his.set[j] = tmp.set[j]; return
false;
}
this.InsertElement(arg2.set[i]);
}
}
return true;
}
// Intersection two IntegerSet public boolean
IntersectIntegerSet(IntegerSet arg1, IntegerSet arg2) {
// either of them is empty
if (arg1.isEmpty == true || arg2.isEmpty == true)
return true;
for (int i = 0; i < this.size; i++)
if (arg2.set[i] != 0 && arg1.isIn(arg2.set[i]) == true)
this.InsertElement(arg2.set[i]);
return true;
}
// insert a element into a IntegerSet
public boolean InsertElement(int arg) {
if (arg < 20 || arg > 80) {
System.out.println("The argument must >20 and <80");
return false;
}
// empty set
if (this.isEmpty == true) {
this.isEmpty = false;
this.current++;
t his.set[0] = arg; return
true;
}
// the set is full
i f (this.current == 10)
r eturn false;
// insert a element in the set
if (this.isIn(arg) == true) {
System.out.println(arg + " is already in the IntegerSet!");
return false;
}
for (int i = 0; i < this.size; i++) {
if (this.set[i] == 0) {
this.set[i] = arg;
t his.current++; return
true;
}
}
// never comes here!
r eturn false;
}
// delete a element in an IntegerSet
p ublic boolean DeleteElement(int arg) {
if (arg < 20 || arg > 80) {
System.out.println("The argument must >20 and <80");
return false;
} // empty set if
(this.isEmpty == true)
// empty InsegerSet
return false;
else {
if (this.isIn(arg) == true) {
int pos = size - 1;
for (int i = 0; i < size; i++)
if (this.set[i] == arg)
pos = i;
this.current--;
// empty?
if (this.current == 0)
this.isEmpty = true;
// set 0
this.set[pos] = 0;
return true;
} else {
System.out.println(arg + " is not in the IntegerSet!");
return false;
}
}
}
// valid public boolean valid() {
for (int i = 0; i < this.size; i++) {
if (this.set[i] == 0)
continue;
if (this.set[i] < 20 || this.set[i] > 80)
return false;
}
return true;
}
// equal
public boolean equal(IntegerSet arg) {
f or (int i = 0; i < size; i++) if
(this.isIn(arg.set[i]) == false)
return false;
r eturn true;
}
// is in?
public boolean isIn(int arg)
{ // empty IntergerSet if
(this.isEmpty == true)
return false;
for (int i = 0; i < size; i++)
if (arg == set[i])
return true;
return false;
}
// print the IntegerSet public
void print() {
S ystem.out.print("( "); for (int i =
0; i < this.size; i++)
System.out.print(this.set[i] + " ");
System.out.print(")\n");
}
//////////////////////////////////////////////////////////////////////////////////////// // for test
// main
public static void main(String[] args) {
IntegerSet t1 = new IntegerSet();
IntegerSet t2 = new IntegerSet();
IntegerSet t3 = new IntegerSet();
IntegerSet t4 = new IntegerSet();
t1.InsertElement(30);
t1.InsertElement(33);
t1.InsertElement(38);
S ystem.out.println("t1"); t1.print();
t2.InsertElement(30);
t2.InsertElement(32); t2.InsertElement(38);
t2.InsertElement(43);
t2.InsertElement(54);
System.out.println("t2");
t2.print();
t3.MergeIntegerSets(t1, t2);
t3.print();
t4.IntersectIntegerSet(t1, t2);
t4.print();
}
}
第4 章习题6
写一个具有两个方法的基类base,并在第一方法内调用第二方法。

然后写一个派生类derived,并覆盖父类中的第二个方法。

产生一个derived 类对象,将它向上类型转换(即转换为base 类型),并调用第一个方法。

验证并解释运行结果。

// 程序清单
/*
* upCast.java
*/
class base {
public void method1() {
System.out.println("method1 is invoked in base!");
S ystem.out.println("Call method2 !");
method2();
}
public void method2() {
System.out.println("method2 is invoked in base!");
}
}
class derived extends base{
p ublic void method2(){
System.out.println("method2 is invoked in derived!");
}
}
public class upCast {
public static void main(String[] args) {
d erived tmp = new derived();
((base)tmp).method1();
}
}
编程证明:接口内的数据成员被自动设置为 static 和 final。

程序内容:
package staticandfinal;
/*
* staticAndFinal.java
*/ interface inter{
int x=2;
}
class derived implements inter{
}
public class StaticAndFinal{
public static void main(String args[]){
inter in=new derived();
// in.x=100; // 不能赋值
System.out.println(in.x+" "+derived.x);
}
}
编写一个类,它具有一个 protected 数据成员。

在同一个文件内再编写第二个类,在这个类内编写一个方法,以操作第一类内的 protected 数据成员。

程序内容:
package pro;
/*
* Pro.java
*/
class class1{
protected int arg;
}
class class2{
public void function1(){
// System.out.println(class1.arg); // 不能操作该变量
System.out.println("调用结束!");
}
}
public class Pro {
public static void main(String[] args) {
class1 c1 = new class1();
class2 c2 = new class2();
c2.function1();
}
}
采用 public、private、protected 以及默认等类型创建一个类,然后定义这个类的一个对象。

观察在访问所有类成员时会出现哪种类型的编译错误。

程序内容:
package testclass;
class Test{
public String pub;
private String pri;
protected String prot;
String fri;
Test(){
this.pub = "public";
this.pri = "private";
this.prot = "protected";
this.fri = "friendly";
}
}
public class Testclass {
public static void main(String[] args) {
Test tmp = new Test();
System.out.println(tmp.pub);
System.out.println(tmp.prot);
System.out.println(tmp.fri);
System.out.println(tmp.pri);
}
}
编写一个类,它具有public、private、protected 以及默认等类型的成员,将这个类存放在某个包中。

在另外一个包内再写第二个类,在此类内编写一个方法,以操作第一类内的各个数据成员,观察在访问所有类成员时会出现哪种类型的编译错误。

程序内容:
包Testclass1中:
package Testclass1;
public class Testclass1{
public String pub;
private String pri;
protected String prot;
String fri;
public T estclass1(){
this.pub = "public";
this.pri = "private";
this.prot = "protected";
this.fri = "friendly";
}
}
包Testclass2中:
package testclass2;
import Testclass1.*;
public class Testclass2 {
public static void main(String[] args) {
Testclass1 tmp;
tmp = new Testclass1();
System.out.println(tmp.pub);
System.out.println(tmp.pri);
System.out.println(tmp.prot);
System.out.println(tmp.fri);
}
}
编写一个采用随机函数生成句子的游戏。

现有4个字符串数组:article、noun、verb、preposition,它们的内容分别是:
the、a 、one 、some、any ;
boy、girl、dog、town、car ;
drove、jumped、ran、walked、skipped和
to、from、over、under、on。

依照句法要求:article + noun + verb + preposition + article + noun,编写程序以产生 20 个句子。

程序内容:
package sentence;
import java.util.* ;
import java.awt.*;
import java.applet.*;
public class Sentence extends Applet {
Random r=new Random ();
String list[][]={{"the","a","one","some","any"},
{"boy","girl","dog","town","car"},
{"drove","jumped","ran","walked","skiped"},
{"to","from","over","'under","on"},
{"the","a","one","some","any"},
{"boy","girl","dog","town","car"} };
TextArea output;
Button m;
int b,c;
public void init() {
output=new TextArea(25,50);
m=new Button("开始");
add(output);
add(m);
}
public boolean action(Event e,Object o){
output.setText ("");
if(e.target==m){
for(int i=0;i<20;i++){
output.appendText((i+1)+" ");
for(int j=0;j<6;j++){
c=(int)(5*r.nextFloat ());
output.appendText((list[j][c])+" ");
}
output.appendText(".\n");
}
}
return true;
}
}
编写一个程序,输入一行文本,采用 StringTokenizer 类的对象,将该文本符号化,并以逆序输出语言符号。

程序内容:
package strtoken;
import java.util.* ;
import java.awt.*;
import java.applet.*;
public class StrToken extends Applet{
String Text;
TextField Input;
Label Lab;
TextArea Output;
public void init(){
Lab = new Label("输入文本: ");
Input = new TextField(40);
Output = new TextArea(10,40);
add(Lab);
add(Input);
add(Output);
Output.setEditable(false);
}
public boolean action(Event e,Object o){
StringTokenizer Token;
if (e.target == Input){
String str = o.toString();
Token = new StringTokenizer(str);
Output.setText("");
Output.appendText("符号个数: "+Token.countTokens()+"\n 符号:\n");
int count = Token.countTokens();
String allstr[] = new String[count];
for (int i = 0;i < count;i++)
allstr[i] = Token.nextToken();
for (int i = count - 1;i >= 0;i--)
Output.appendText( allstr[i] + "\n" );
}
return true;
}
}
日期的常用格式具有如下两种:
2012-11-29 和 November 29, 2012
从键盘读入第一种形式的日期,编程输出第二种形式的日期。

程序内容:
package datachange;
import java.io.*;
class Date1 {
public int year;
public int month;
public int day;
Date1(){
}
Date1(int y,int m,int d){
this.year=y;
this.month=m;
this.day=d;
}
void print(){
System.out.println(this.year+"-"+this.month+"-"+this.day);
}
}
class Date2 {
public String month;
public int year;
public int day;
Date2(){
}
Date2(String month, int year, int day) {
this.month = month;
this.year = year;
this.day = day;
}
public void ChangeToDate(Date1 date) {
String Month[] =
{
"January","Februry","March", "April", "May","June", "July", "August", "September","October","November","December" };
this.month = Month[date.month - 1];
this.year = date.year;
this.day = date.day;
}
public void print(){
System.out.println(this.month+" "+this.day+","+this.year);
}
}
public class DataChange {
public static void main(String args[ ])
throws IOException{
int y=0,m=0,d=0;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String line;
System.out.print("Enter Year: ");
line=in.readLine( );
if(line!=null)
y=Integer.parseInt(line);
System.out.print("Enter Month: ");
line=in.readLine( );
if(line!=null)
m=Integer.parseInt(line);
System.out.print("Enter day: ");
line=in.readLine( );
if(line!=null)
d=Integer.parseInt(line);
Date1 date1= new Date1(y,m,d);
date1.print();
Date2 date2 = new Date2();
date2.ChangeToDate(date1);
date2.print();
}
}
4、从键盘输入几行文本作如下处理:
(1) 显示各元音字母出现的次数。

(2) 统计各个单词的长度。

程序内容:
package countwords;
import java.io.*;
import java.util.*;
public class CountWords {
public static void main(String args[ ])
throws IOException{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String line , wordCount[];
StringTokenizer token;
int num,k,a,e,i,o,u;
a=e=i=o=u=0;
while(true){
line=in.readLine( );
if(line!=null){
for(k=0;k<line.length();k++)
switch (Character.toUpperCase(line.charAt(k))){ case 'A' : a++; break;
case 'E' : e++; break;
case 'I' : i++; break;
case 'O' : o++; break;
case 'U' : u++; break;
default : break;
}
System.out.println("\n\n 各个元音字母的个数为:");
System.out.println("a: " + a);
System.out.println("e: " + e);
System.out.println("i: " + i);
System.out.println("o: " + o);
System.out.println("u: " + u);
token=new StringTokenizer(line);
num=token.countTokens( );
wordCount=new String[num];
k=0;。

相关文档
最新文档