编程题:
常用类
1.编写一个方法判断一个字符串在另一个字符串中出现的次数。
(提示:方法头: int
getCount(String substr,String str)
)
int getCount(String substr,String str){
int count=0;
int index=0;
while((index=str.indexOf(substr,index))>=0){
index++;
count++;
}
return count;
}
2.编写一个方法为物品生成一个指定长度的编号,要求编号的每一位或者为0到9的数字,或者为A到Z的大写字母,每次产生的编号是随机的。
String getId(int length)
{
// 26个字母和10个数字,共36个符号,
//随机生成0到35的数字分别对应到字母和数字
StringBuffer sb=new StringBuffer();
for(int i=0;i<length;i++)
{
int tmp =(int)( Math.random()*36);
if(tmp<10)
sb.append((char)('0'+tmp));
else
sb.append((char)('A'+tmp-10));
}
return sb.toString();
}
3.编写一个方法,将一个整型数组按照升序重新排序;
public class BubbleSort
{
public static
void bubbleSort(int[] a)
{
int n=a.length;
int temp;
for(int i=n-1;i>0;i--)
{
for(int j=0;j<i-1;j++)
{
if(a[j+1]<a[j])
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
}
public
static void main(String[] args)
{
int[] m={10,8,21,65,32,51,74,14,28,95};
System.out.println(“排序前的数组:”);
for(int i=0;i<m.length;i++)
System.out.print(m[i]+” ”);
bubbleSort(m);
System.out.println();
System.out.println(“排序后的数组:”);
for(int i=0;i<m.length;i++)
System.out.print(m[i]+” ”);
}
}
4.编写一个方法验证一个字符串是否是合法的Email,合法的EMail格式为:zhang@a.com。最少要有3部分组成,第一部分是用户名,后面是“@”符号,第二部分是公司的名字,最后是组织类别,中间以“.”分开。
boolean isEmail(String str)
{
if(str==null)
return false;
int index1=str.indexOf("@");
int index2=str.indexOf(".");
if(index1<1 || index1+1 >=index2 ||
index2==str.length()-1)
return false;
else
return
true;
}
5.编写一个方法验证用户输入的日期格式是否正确,要求格式为:2006/12/12。方法的参数是要验证的日期字符串,如果格式正确返回true,否则返回false。
import
java.text.*;
class
Exc8_7
{
public static void main(String[] args)
{
System.out.println(isDate("2007/5/1"));
System.out.println(isDate("2007"));
}
public static boolean isDate(String str){
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
try{
java.util.Date d = df.parse(str);
System.out.println(d.toString());
return true;
}catch(Exception e){
return false;
}
}
}
6.编写一个用户管理类(UserManager),在类中定义一个Vector类型的成员变量,该变量保存所有的用户,用户对应的类型为User(User定义如下)。在类中定义如下几个方法:
1.
添加一个用户。
2.
删除一个用户。
3.
判断一个用户是否存在。
4.
显示所有用户信息(User对象有toString方法可以显示用户信息)。
public
class User
{
private String name;
public User(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public String toString()
{
return "User:"+name;
}
public boolean equals(Object o)
{
return name.equals(((User)o).name);
}
}
答案:
import
java.util.*;
public
class UserManager {
private Vector users;
public UserManager() {
}
//
添加用户
public void addUser(User u){
if(users==null)
users=new Vector();
users.add(u);
}
//
删除用户
public void deleteUser(User u) throws Exception{
if(users==null)
throw new Exception("不存在用户");
else
users.remove(u);
}
//
判断用户是否存在
public boolean isExist(User u){
if(users==null)
return false;
else
return users.contains(u);
}
//
显示所有用户信息
public void print(){
System.out.println("*****************");
Iterator i = users.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
System.out.println("*****************");
}
}
1、编写程序输出以下信息:
**************************
*
Welcome To
Java!
*
**************************
(答案:
public
class Test{
public static void main(String[] args){
System.out.println("**************************");
System.out.println("*
Welcome To
Java!
*");
System.out.println("**************************");
}
}
)
2、编写程序计算半径为5的圆的面积,计算公式为:面积=半径*半径*圆周率
(答案:
public
class Test{
public static void main(String[] args){
double radius=5.0;
double area;
final double PI = 3.14159;
area= radius * radius*PI;
System.out.println(area);
}
}
)
3、编写程序将华氏温度78度转换为摄氏温度,转换成的摄氏温度在屏幕上显示出来:
转换公式为:摄氏度=(5/9)*(华氏度-32)
(答案:
public
class Test{
public static void main(String[] args){
double hs=78.0;
double cs;
cs=(5.0/9)*(hs-32);
System.out.println(cs);
}
}
)
4、编写程序计算底边长为7、高为3的三角形的面积。
计算公式为:三角形面积=底边长*高/2
(答案:
public
class Test{
public static void main(String[] args){
double l=7;
double h=3;
double area=l*h/2;
System.out.println(area);
}
}
)
5、编写程序,打印汉字’我’在unicode码中对应的十进制编码:
(答案:
public
class Test{
public static void main(String[] args){
char c='我';
int i=c;
System.out.print(i);
}
}
)
编程题:
1.用while循环,求1-100的和
public
class Exercise2_1
{
public static void main(String[ ] args)
{
int I = 1;
int sum = 0;
while(i<=100)
{
sum += i;
i++;
}
System.out.println(sum);
}
}
2.编写程序输出1-20之间的偶数
public
class DoWhileTest {
public static void main(String[] args) {
int i=1;
do
{
if(i%2==0)
System.out.println(i+"
");
i++;
}while(i<=20);
}
}
3.水仙花数是指个位、十位和百位三个数的立方和等于这个三位数本身的数,编写程序求出所有的水仙花数。
答案:
public
class Narcissus
{
public static void main(String args[])
{
int i, j, k;
for(int num = 101; num <=999; num++)
{
i = num %
10;
//个位数
j =num/ 10 %
10;
//十位数
k = num /
100;
//百位数
if(i * i * i + j * j * j + k * k * k ==
num)
System.out.print(num + "\t");
}
}
}
4.编写一个Java应用程序,用循环结构打印如下的数值列表:
N
10*N
100*N
1000*N
1
10
100
1000
2
20
200
2000
3
30
300
3000
4
40
400
4000
5
50
500
5000
答案:
public
class Table {
public static void main(String [] args)
{
int n = 1;
System.out.println(“N\t10*N\t100*N\t1000*N\n”);
while ( n <= 5) {
System.out.println (n
+”\t”+(10*n) +”\t”+(100*n) +”\t” +(1000*n));
n++;
}
}
}
5.编写一个应用程序,计算1~10之间的各个整数的阶乘,并将结果输出到屏幕上。
答案:
public
class Factorial {
public static void main (String []
args){
for (int number =1 ; number <=10 ;
number++) {
int factorial
= 1;
for (it
smaller = 1; smaller <= number ;
smaller++)
factorial *= smaller ;
System.out.println(number +”! is ”+ factorial);
}
}
}
6.用while循环求n2大于12000的最小数n。
public
class Exercise2_6
{
public static void main(String[]
args)
{
int
i = 1;
while (i*i <= 12000 )
{
i++;
}
System.out.println("This number is "+i);
}
}
7.打印2到10000的所有素数,每行显示8个素数。
public
class Exercise2_7
{
public static void main(String[] args)
{
boolean isPrime=false;
int count=0;
int i=2;
while(i<=10000)
{
isPrime=true;
int j=2;
while(j<i/2)
{
if(i%j==0)
{
isPrime=false;
break;
}
j++;
}
if(isPrime)
{
count++;
if(count%8==0)
System.out.println("
"+i);
else
System.out.print("
"+i);
}
i++;
}
}
}
8.写一个嵌套的for循环打印下列图案:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
答案:
public class Exercise2_9
{
public static void main(String[] args)
{
for(int i=1;i<6;i++)
{
for(int j=1;j<=i;j++)
if(i==j)
{
System.out.println(i);
}
else
{
System.out.print(j+" ");
}
}
}
}
9.编写JAVA Application,要求输出一个如下图的菱形。
*
*
*
*
*
*
*
*
*
*
*
*
*
答案:
import
java.io.*;
public
class Star
{
public static void main(String args[])
{
int num = 5;
for(int i = 1;i <= num;i +=2)
{
for(int j = 1;j < num -
i;j+=2)
System.out.print(" ");
for(int k = 1;k <=
i;k++)
System.out.print("* ");
System.out.println();
}
for(int i = num - 2;i >= 1;i -=2)
{
for(int j = 1; j < num -
i;j+=2)
System.out.print(" ");
for(int k = 1;k <=
i;k++)
System.out.print("* ");
System.out.println();
}
}
}
10.编写一个主类Triangle,要求在它的main方法中写一个嵌套的for循环,通过这个嵌套的循环在屏幕上打印下列图案:
1
1
2 1
1
2
3
2 1
1
2
3
4
3
2 1
1
2
3
4
5
4
3
2 1
1
2
3
4
5
6
5
4
3
2 1
1
2
3
4
5
6
7
6
5
4
3
2 1
1
2
3
4
5
6
7
8
7
6
5
4
3
2 1
答案:
public
class Triangle
{
public static void main(String[] args)
{
for(int row =0; row <=7; row
++)
{
//print blanks
for(int column =1; column <=7- row; column
++)
System.out.print(" ");
//print left half of the row
for(int column =1; column <= row +1; column
++)
{
System.out.print(" "+
column);
}
//print right half of the row
for(int column = row ; column >0; column
--)
{
System.out.print(" "+
column);
}
//start a new line
System.out.println();
}
}
}
11、输出1到100中能被7整除或者个位数是7的数字
public
class Ex2_11
{
public static void main(String[] args)
{
for(int i=1;i<=100;i++)
{
if((i%7==0)||(i==7))
System.out.println(i);
}
}
}
12、有三个整型变量a、b和c,编写程序求3个数中的最大值
public
class Ex2_12
{
public static void main(String[] args)
{
int a=5,b=6,c=7;
int max=0;
if(a>b)
max = a;
else
max = b;
if(max<c)
max = c;
System.out.println(max);
}
}
13、输出1~100这100个数
public
class Ex2_13
{
public static void main(String[] args)
{
for(int i=1;i<=100;i++)
{
System.out.println(i);
}
}
}
14、编写一个程序把十进制的数转换成一个二进制的数
public
class Ex2_14
{
public static void main(String[] args)
{
int number = 26;
int temp = 0;
String result =””;
while(number!=0)
{
temp = number%2;
result = temp + result;
number = number / 2;
}
System.out.println(result);
}
}
1.
编写一个方法,用来计算并输出:
1-1/2+1/3-1/4+………+(-1)(n-1)
*1/n,其中n是用户输入的正整数。
public
class ShuLie
{
public static void sum(int n)
{
int sign=-1;
double
sum=1.0;
double
under=1.0;
for(int
i=2;i<=n;i++)
{
under=1.0*i;
sum=sum+sign/under;
sign=sign*(-1);
}
System.out.println(“计算结果是:”+sum);
}
public static void main(String[] args)
{
System.out.println(“请输入整数n:”);
int
n=MyInput.readInt();
sum(n);
}
}
2.编写方法,输出n以内的所有完数。
完数:如果一个数恰好等于它的因子之和,则这个数就是“完数”。例如:6的因子是1、2、3,而6=1+2+3,因此6就是完数。
public
class Wanshu
{
public static void
qiuwanshu(int n)
{
int i,j,sum;
for(i=1;i<=n;i++)
{
sum=0;
for(j=1;j<i;j++)
if(i%j==0)
sum+=j;
if(i==sum)
System.out.print(i+” ”);
}
Sytem.out.println();
}
public static void
main(String[] args)
{
System.out.println(“请输入整数n,我们将给出n以内的所有完数:”);
int
n=MyInput.readInt();
qiuwanshu(n);
}
}
3.编写方法,求如下数值:1+1/3+
… +
… +1/(2n-1);
public
class TestMain
{
public static void main(String[]
args)
{int n;
System.out.print(“please input an integer:”);
n=MyInput.ReadInt();
System.out.println("1+1/3+
… +
… +1/(2n-1)=
"+sum(n));
}
public static double sum(int
n)
(int i=1;
double
s=0.0;
while
(i<=n)
{ s+=1/(2*i-1);
i++;}
return s;
}
}
4.
编写方法求一个double数值的向右取整,再写一个方法求它的向左取整。数d的向右取整是大于等于d的最小整数,d的向左取整是小于d的最大整数。例如,5.4的向右取整是整数6而向左取整是5。
public
class TestMain
{
public static void main(String[]
args)
{ double n;
System.out.print(“please input an double number:”);
n=MyInput.readDouble();
System.out.println(right(n));
System.out.println(left(n));
}
public static int right(double
n)
{
int result = (int)n;
if(n > result)
return result + 1;
else
return result;
}
public static int left(double
n)
{
return (int)n;
}
}
5.编写方法,计算一个整数各位数字的和。使用如下方法说明:
public static int sumDigits(long n)
例如:sumDigits(234)返回2+3+4=9
public
class TestMain
{
public static void main(String[]
args)
{
long
number = 234;
System.out.println(sumDigits(number));
}
public static int sumDigits(long
n)
{
int
sum=0;
while(n>0)
{
sum += n;
n=n/10;
}
return sum;
}
}
1.定义一个类,描述一个矩形,包含有长、宽两种属性,和计算面积方法。
编写一个类,继承自矩形类,同时该类描述长方体,具有长、宽、高属性,和计算体积的方法。
编写一个测试类,对以上两个类进行测试,创建一个长方体,定义其长、宽、高,输出其底面积和体积。
public
class TestExtends{
public static void main(String[] args){
LiFangTi f=new LiFangTi();
f.length=2;
f.width=3;
f.height=7;
System.out.println("立方体的底面积为:"+f.findArea()+"立方体的体积为:"+f.findVolume());
}
}
class
JuXing{
int length;
int width;
int findArea(){
return length*width;
}
}
class
LiFangTi extends JuXing{
int height;
int findVolume(){
return findArea()*height;
}
}
2.
实现一个名为Person的类和它的子类Employee,Employee有两个子类Faculty和Staff。
具体要求如下:
(1)Person类中的属性有:姓名name(String类型),地址address(String类型),电话号码telphone(String类型)和电子邮件地址email(String类型);
(2)Employee类中的属性有:办公室office(String类型),工资wage(double类型),受雇日期hiredate(String类型);
(3)Faculty类中的属性有:学位degree(String类型),级别level(String类型);
(4)Staff类中的属性有:职务称号duty(String类型);
class
Person
{
String name ;
String address;
String telphone;
String email;
public String toString()
{
return "[Person]"+name;
}
}
class
Employee extends
Person
{
String office;
Double wage;
String hiredate;
public String toString()
{
return "[Employee]"+name;
}
}
class
Faculty extends Employee
{
String degree;
String level;
public String toString()
{
return "[Faculty]"+name;
}
}
class
Staff extends Employee
{
String duty;
public String toString()
{
return "[Staff]"+name;
}
}
编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数wheels和车重weight。小车类Car是Vehicle的子类,其中包含的属性有载人数loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个类都有构造方法和输出相关数据的方法。
答案:
class
Vehicle
{
int wheels;
float
weight;
Vehicle(int wh,float we)
{
wheels=wh;
weight=we;
}
int
getWheels(){return wheels;}
float
getWeight(){return weight;}
void
show()
{
System.out.println(“车轮:”+wheels);
System.out.println(“车重:”+weight);
}
}
class Car
extends Vehicle
{
int loader;
Car(int wheels,float weight,int
loader)
{super(wheels,weight);
this.loader=loader;}
}
public
void show()
{
System.out.println(“车型:小车”);
super.show();
System.out.println(“载人:”+loader);
}
class
Truck extends Car
{
float payload;
Truck(int wheels,float weight,int
loader,float payload)
{super(wheels,weight,loader);
this.payload=payload;}
}
public
void show()
{
System.out.println(“车型:卡车”);
super.show();
System.out.println(“载重量:”+payload);
}
public
class VehicleClient
{
public static void
main(String[] args)
{
Car car=new Car(4,1500,4);
car.show();
Truck truck=new
Truck(8,7000,3,25000);
truck.show();
}
}
4.
一个关于等边三角形的类Trival如下,其中的属性包括三角形的bian,方法包括:默认构造方法、为bian指定初值的构造方法、获取三角形面积findArea()。试利用方法覆盖的知识,设计三棱柱体类TriCylinder。(其中findArea()为计算三棱柱体的表面积)
class
Trival
{
double bian;
Trival()
{
bian=1.0;
}
Trival(double b)
{
bian=b;
}
double findArea()
{
return (Math.sqrt(3)/4)*bian*bian;
}
}
答案:
public
class TestOverrideMethods
{
public static void main(String[]
args)
{
Cylinder myTriCylinder = new TriCylinder(5.0, 2.0);
System.out.println("The length is " +
myTriCylinder.getLength());
System.out.println("The radius is " +
myTriCylinder.getRadius());
System.out.println("The surface area of the Tricylinder is
"+
myTriCylinder.findArea());
}
}
class
TriCylinder extends Trival
{
private double length;
// Default constructor
public Cylinder()
{
super();
length = 1.0;
}
public Cylinder(double r, double l)
{
super(r);
length = l;
}
// Getter method for length
public double getLength()
{
return length;
}
public double findArea()
{
return 2*( Math.sqrt(3)/4)*bian*bian +3*bian*length;
}
}
5.定义一个Document类,包含成员属性name。从Document派生出Book子类,增加pageCount属性,编写一个应用程序,测试定义的类。
class
Document
{
String name;
Document()
{}
Document(String name)
{
this.name = name;
}
}
class Book
extends Document
{
int pageCount
Book(String name , int pageCount)
{
Super(name);
this.pageCount = pageCount;
}
}
6.定义名为VolumeArea的抽象类,在其中定义圆周率p的值为3.14159,并定义两个抽象方法volume(double
r)和area(double
r),它们的返回值类型均为float。再定义以类VolumeArea为父类的子类VolumeAndArea,在该子类中实现父类中的抽象方法:方法volume(double r)
的功能是求半径为r的球的体积(公式为:4pr3¸3);方法area(double
r)的功能是求半径为r的圆的面积(公式为:pr2)。请编写一个Application
,在其主类中定义一个VolumeAndArea类的对象x,通过对象x求半径为r(r的值由命令行给定)的球的体积及该球最大切面的圆的面积,并输出计算结果。
import
java.util.*;
abstract
class VolumeArea{
public static final double PI = 3.14159;
public abstract float volume(double r);
public abstract float area(double r);
}
class
VolumeAndArea extends VolumeArea{
public float volume(double r){
return (float)(4*PI*r*r*r/3);
}
public float area(double r){
return (float)(PI*r*r);
}
}
class
Test{
public static void main(String[ ] args){
VolumeAndArea x = new VolumeAndArea();
System.out.print ("please input : ");
Scanner sc = new Scanner(System.in);
String str = sc.next();
double r = Integer.parseInt(str);
System.out.println ("volume : "+x.volume(r));
System.out.println ("area : "+x.area(r));
}
}
关于借口类的定义练习:
1.
利用接口继承完成对生物、动物、人三个接口的定义。其中生物接口定义呼吸抽象方法;动物接口除具备生物接口特征之外,还定义了吃饭和睡觉两个抽象方法;人接口除具备动物接口特征外,还定义了思维和学习两个抽象方法。定义一个学生类实现上述人接口。
interface
Biology
{
void breath();
}
interface
Animal extends Biology
{
void eat();
void sleep();
}
interface
Human extends Animal
{
void think();
void study();
}
class
Student implements Human
{
void breath()
{
System.out.println(“breathing”);
}
void eat()
{
System.out.println(“eating”);
}
void sleep()
{
System.out.println(“sleeping”);
}
void think()
{
System.out.println(“thinking”);
}
void study()
{
System.out.println(“study”);
}
}
2.
定义一个接口CanFly,描述会飞的方法public void fly();
分别定义类飞机和鸟,实现CanFly接口。
定义一个测试类,测试飞机和鸟。测试类中定义一个makeFly()方法,让会飞的事物飞起来。然后在main方法中创建飞机对象和鸟对象,并在main方法中调用makeFly()方法,让飞机和鸟起飞。
interface
CanFly
{
public void fly();
}
class
AirPlane implements CanFly
{
public void fly()
{
System.out.println(“airplane is flying”);
}
}
class Bird
implements CanFly
{
public void fly()
{
System.out.println(“Bird is flying”);
}
}
class
Test
{
static makeFly(CanFly obj)
{
obj.fly();
}
public static void main(String[] args)
{
AirPlane ap = new AirPlane();
Bird b = new Bird();
makeFly(ap);
makFly(b);
}
}
3.
接口Volume如下,试定义三棱柱类TriVolume,该类实现了Volume接口,其中三棱柱的底面为等边三角形。
接口为:
public
interface Volume
{
public double findVolume();
}
class
TriVolume implements Volume
{
double bian,length;
TriVolume(double b, double l)
{
bian = b;
length=l;
}
public double findVolume()
{
return (Math.sqrt(3)/4)*bian*bian*length;
}
}
初识return语句
1. 以下方法fun的功能是求两参数之积。(return a*b)
int fun ( int a, int b
) {
__________________;
}
2.
以下方法fun的功能是求两参数之积。(return (float)a*b)
float fun ( int a, double b
) {
__________________;
}
3. 以下方法fun的功能是求两参数的最大值。(return
a>b?a:b)
int fun ( int a, int b
) {
__________________;
}
4.以下方法m的功能是求两参数之积的整数部分。
(return (int)(a*b))
int m ( float x, float y
) {
__________________; }
5.
下面是用户程序对Applet
类中方法paint( )
的重新定义。
(void
call)
public ___ paint(Graphics
____)
{
call.drawString("Hello,java!",10,20); }
6.下面方法的功能是判断一个整数是否为偶数,将程序补充完整。(boolean
true)
public ________ is Even(int
a)
{
if(a%2==0)
return _____;
else
return false;
}
三
加载中,请稍候......