期末复习JAVA题

更新时间:2024-01-05 19:12:01 阅读量: 教育文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

1. 分解质因数 package d2;

import java.util.Scanner;

public class Zys {

public static void main(String[]args){ Scanner sc=new Scanner(System.in); System.out.print(\请输入一个数:\ int a=sc.nextInt(); int n=2;

System.out.println(a+\ while(a>=n){ if(a%n==0){

System.out.print(n+\ a=a/n; }

if(a%n!=0){ n++; } } } }

2. 判断是否是回文数

ackage c2;

import java.util.Scanner;

public class huiwenshu {

public static void main(String[]args){ //System.out.println(\请输入一个数\ Scanner a=new Scanner(System.in); System.out.println(\请输入一个数\ String b=a.nextLine(); boolean c=false; for(int i=0;i

c=false; } else c=true; if(c==true) System.out.println(\是回文数\ }else{

System.out.println(\不是回文数\

} }

}

3. 数组逆序输出

public class sz {

public static void main(String[]args){ int a[]={1,2,3,4,5,6,7,8,9,0}; for(int i=9;i>=0;i--){ System.out.println(a[i]); } } }

4. 水仙花数

public class sxh {

public static void main(String[]args){ int a,b,c; for(int i=100;i<=999;i++){ a=i/10; b=i; c=i/100; if(i==a*a*a+b*b*b+c*c*c) System.out.println(i); } } } 5. 素数

public class Sushu {

public static void main(String[] args){ for(int i=100;i<=200;i++){ boolean b=false; for(int j=2;j<=Math.sqrt(i);j++ ){ if(i%j==0){ b=true;break; } else {b=false;} } if (b==false) System.out.println(i); } } }

6.最大公约数和最小公倍数

import java.util.Scanner; public class Sz { public static void main(String[] args) { int a, b, m; Scanner s = new Scanner(System.in); System.out.print(\键入一个整数: \ a = s.nextInt(); System.out.print(\再键入一个整数: \

b = s.nextInt(); deff cd = new deff(); m = cd.deff(a, b); int n = a * b / m; System.out.println(\最大公约数: \m);

System.out.println(\最小公倍数: \n);

} }

class deff { public int deff(int x, int y) { int t; if (x < y) { t = x; x = y; y = t; } while (y != 0) { if (x == y) return x; else { int k = x % y; x = y; y = k; } } return x; } }

1、题目:一个数如果恰好等于它的因子之和,这个数就称为 \完数 \。例如6=1+2+3.编程 找出1000以内的所有完数。 public class shishu {

public static void main(String[] args) { int i;

for (i = 2; i <= 1000; i++) { int sum = 0; for (int j = 1; j <=i/2; j++) { if (i % j == 0) {

// System.out.println(j); sum = sum + j; } }

if (sum == i) {

System.out.println(i); }

}

} }

2. 假如我们在开发一个系统时需要对员工进行建模,员工包含3个属性:姓名、工号以及工资。经理也是员工,除了含有员工的属性外,另外还有一个奖金属性。请使用继承的思想设计出员工类和经理类。要求类中提供必要的方法进行属性访问。

public class manager extends yg{ protected int award;

public static void main(String[]args){ yg a=new yg();

a.setdata(\张晓晓\ a.print();

manager b=new manager();

b.setdata(\黄洋洋\ b.award=20000; b.print();

System.out.println(\奖金\ } }

class yg {

protected String name; protected String num; protected int salary;

void setdata(String xm,String gh,int gz){ name =xm; num=gh; salary=gz; }

public void print(){

System.out.println(\姓名:\ System.out.println(\工号\ System.out.println(\工资\} }

3. 以点类作为基类,从点派生出圆,从圆派生圆柱,设计成员函数输出它们的面积和体积。

package third;

public class Circle extends point{ protected int r;

Circle(int r,int x,int y){ super(x,y); this.r=r; }

public double area(){ return 3.14*r*r; }

package third;

public class Cyliner extends Circle { protected int h;

Cyliner(int h,int x,int y,int r){ super(x,y,r); this.h=h; }

public double volume(){ return area()*h; }

public static void main(String[]args){ Circle a=new Circle(2,2,4); Cyliner b=new Cyliner(2,2,3,4);

System.out.println(\圆的面积是:\ System.out.println(\圆的体积是:\} } }

public class point { protected int x; protected int y; point(){

this.x=0; this.y=0; }

point(int x,int y){ this.x=x; this.y=y; } }

4.定义一个抽象基类Shape,它包含三个抽象方法center()、diameter()、getArea(),从Shape类派生出Square和Circle类,这两个类都用center()计算对象的中心坐标,diameter()计算对象的外界圆直径,getArea()方法计算对象的面积。编写编写应用程序使用Rectangle类和Circle类。 package W1; public abstract class Shape {

abstract void center();

abstract void diameter(); abstract void getArea(); }

package W1;

public class Square extends Shape{ @Override

void center() { }

@Override

void diameter() { } @Override void getArea() { } }

package W1;

public class Circle extends Shape{ @Override void center() { } @Override

void diameter() { } @Override

void getArea() { } }

package W1;

public class Rectangle extends Square{ }

package W1;

public class Test {

public static void main(String[] args) {

Circle c = new Circle(); Square r = new Rectangle(); c.center(); c.diameter();

c.getArea(); r.center(); r.diameter(); r.getArea();

} }

实现一个名为Person的类和它的子类Employee, Manager是Employee的子类,设计一个接口Add用于涨工资,普通员工一次能涨10%,经理能涨20%。

具体要求如下: (1)Person类中的属性有:姓名name(String类型),地址address(String类型)并写出该类的构造方法; (2)Employee类中的属性有:工号ID(String型),工资wage(double类型),工龄(int型),写出该类的构造方法; (3)Manager类中的属性有:级别level(String类型),写出该类的构造方法;

public class person { private String name; private String address;

public person(String name2, String address2) { }

public void Person(String n,String a){ this.setName(n); this.setAddress(a); }

public void setName(String n){ this.name = n; }

public void setAddress(String a){ this.address = a; }

private String getName(){ return this.name; }

private String getAddress(){ return this.address; } }

lass Empolyee extends person{ private int employeeNo; private double pay; private int age; public Empolyee(String name,String address,int empolyeeNO, double pay,int age){ super(name,address);

this.setEmployeeNo(empolyeeNO); this.setPay(pay); this.setAge(age); }

public void setEmployeeNo(int e){ this.employeeNo = e; }

public void setPay(double p){ this.pay = p; }

public void setAge(int a){ this.age = a; }

public int getEmployeeNo(){ return this.employeeNo; }

public double getPay(){ return this.pay; }

public int getAge(){ return this.age; } }

class Manager extends Empolyee{ private int level;

public Manager(String name,String address,int empolyeeNO,double pay, int age,int level){

super(name,address,empolyeeNO,pay,age); this.setLevel(level); }

public void setLevel(int l){ this.level = l; }

public int getLevel(){ return this.level; }

public void printInfo(){

System.out.println(\姓名:\工号:\+\工龄:\级别:\地址:\ System.out.println(\原工资:\

System.out.println(\涨工资后的工资:\Add().addPay(this.getLevel(), this.getPay())); }

private String getAddress() { return null; }

private String getName() { return null; } }

class Add{

public double addPay(int level,double pay){ if(level==0){

pay = (1+0.1)*pay; }

else if(level==1){ pay = (1+0.2)*pay; } else{

System.out.println(\级别只能为0或1,0表示普通员工,1则表示经理,操作无效!\ }

return pay; } }

public class ExtendsDemo {

public static void main(String[] args) { Manager m1 = new Manager(\张三\南京路\

Manager m2 = new Manager(\李四\长江路\ m1.printInfo();

System.out.println(\*************************\ m2.printInfo(); } }

编写一个测试类,产生一个员工和一个经理并输出其具有的信息。

1.定义一个接口Assaultable(可攻击的),该接口有一个抽象方法attack()。

2.定义一个接口Mobile(可移动的),该接口有一个抽象方法move()。

3.定义一个抽象类Weapon,实现Assaultable接口和Mobile接口,但并没有给出具体的实现方法。

4.定义3个类:Tank,Flighter,WarShip都继承自Weapon,分别用不同的方式实现Weapon类中的抽象方法。 5.写一个类Army,代表一支军队,这个类有一个属性是Weapon数组w(用来存储该军队所拥有的所有武器);该类还提供一个构造方法,在构造方法里通过传一个int类型的参数来限定该类所能拥有的最大武器数量,并用这一大小来初始化数组w。该类还提供 一个方法addWeapon(Weapon wa),表示把参数wa所代表的武器加入到数组w中。在这个类中还定义两个方法attackAll()和moveAll(),让w数组中的所有武器攻击和移动。 6.写一个主方法去测试以上程序。

class Army { private Weapon[] w = null; private int size = 0; private Army() { } public Army(int i) { w = new Weapon[i]; } public void addWeapon(Weapon weapon) { if (size >= w.length) { System.out.println(\军队装备足够了!\

return; } else { w[size] = weapon; size++; } } public void attacAll() { for (Weapon wea : w) { if (wea != null) { wea.attack(); } } }

public void moveAll() { for (Weapon wea : w) { if (wea != null) { wea.move(); } } } }

package A1;

class Flighter extends Weapon { public void attack() { System.out.println(\attacks\

} public void move() { System.out.println(\

} }

public class NotSimple { public static void main(String[] args) { Army a = new Army(3); a.addWeapon(new Tank()); a.addWeapon(new Flighter()); a.addWeapon(new WarShip()); a.attacAll(); a.moveAll(); } } interface Assaultable { abstract public void attack(); } interface Mobile { abstract public void move(); } abstract class Weapon implements Assaultable, Mobile { }

class Tank extends Weapon { public void attack() { System.out.println(\attacks\

} public void move() { System.out.println(\ } }

package A1;

class WarShip extends Weapon { public void attack() { System.out.println(\ } public void move() { System.out.println(\ } }

class Army { private Weapon[] w = null; private int size = 0; private Army() { }

public Army(int i) { w = new Weapon[i]; }

public void addWeapon(Weapon weapon) { if (size >= w.length) {

System.out.println(\军队装备足够了!\

return; } else {

w[size] = weapon; size++; } }

public void attacAll() { for (Weapon wea : w) { if (wea != null) { wea.attack(); } } }

public void moveAll() { for (Weapon wea : w) { if (wea != null) { wea.move(); } } }

} package A1;

class Flighter extends Weapon {

public void attack() {

System.out.println(\ }

public void move() {

System.out.println(\ }} package A1;

public class NotSimple {

public static void main(String[] args) { Army a = new Army(3);

a.addWeapon(new Tank()); a.addWeapon(new Flighter()); a.addWeapon(new WarShip());

a.attacAll(); a.moveAll(); }

}

interface Assaultable {

abstract public void attack(); }

interface Mobile {

abstract public void move(); }

abstract class Weapon implements Assaultable, Mobile { } package A1;

class Tank extends Weapon { public void attack() {

System.out.println(\ }

public void move() {

System.out.println(\ } } package A1;

class WarShip extends Weapon { public void attack() {

System.out.println(\ }

public void move() {

System.out.println(\ } }

一个公司有2辆小汽车(car),一辆公共汽车(bus),其中:第一小辆汽车每天跑300公里;第二辆小汽车每天跑400公里;公共汽车每天跑500公里,已知小汽车每百公里耗油量为7升,公共汽车每百公里耗油量为10升,用接口编程计算每天所有交通工具的耗油量。

public interface Vehicle { int getfuel(); }

import c1.Vehicle;

public class bus implements Vehicle { int kil; bus(int k1){kil=k1;} public int getfuel(){ return(10*kil/100); } }

import c1.Vehicle;

class car implements Vehicle { int kil; car(int k1){kil=k1;} public int getfuel(){ return(7*kil/100); } }

import c1.bus; import c1.car;

import c1.company1; import c1.Vehicle;

public class company1 { Vehicle a[]; company1(){ a=new Vehicle[3]; a[0]=new car(300); a[1]=new bus(500); a[2]=new car(400); } int rf(){ int i=0; for(i=0;i

}

编写创建一个box类,在其中定义三个变量表示一个立方体的长、宽和高,定义一个构造方法对这三个变量进行初始化,然后定义一个方法求立方体的体积。创建一个对象,求给定尺寸的立方体的体积。

public class Box { double length; double wide; double high;

Box(double l,double w,double h){ this.length=l; this.wide=w; this.high=h; }

public void volume(){ double v;

v=length*wide*high;

System.out.println(\的体积是:\} }

public class Test {

public static void main(String[]args){ Box a=new Box(2,2,3); a.volume(); } }

定义一个学生类student,属性包括学号、班号、姓名、性别、年龄、班级总人数;方法包括获得学号、获得班号、获得姓名、获得性别、获得年龄、获得班级总人数、修改学号、修改班号、修改姓名、修改性别、修改年龄、以及一个tostring()方法将student类中的所有属性组合成一个字符串。定义一个学生数组对象。设计程序进行测试。

public class Student { private String num; private String grade; private String name; private String sex; private int age; private int count ;

Student(String nu,String gr,String na,String se,int ag,int co){ this.num=nu; this.grade=gr; this.name=na; this.sex=se; this.age=ag; this.count=co; }

public String getNum() { return num; }

public void setNum(String num) { this.num = num; }

public String getGrade() { return grade; }

public void setGrade(String grade) { this.grade = grade; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public String getSex() { return sex; }

public void setSex(String sex) { this.sex = sex; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }

public int getcount() { return count; }

public void setcount(int count) { this.count = count; }

public String toString(){

return \学号\班号\姓名\性别\年龄\班级总人数\ } }

public class Test3 {

public static void main(String[]args){ Student s[]=new Student[2];

s[0]=new Student(\信管131\张晓晓\女\

s[1]=new Student(\信管131\小高密\女\

for(int i=0;i<2;i++){ System.out.println(s[i].toString()); }

} }

设计一个人员类person,其中包含一个方法pay,代表人员的工资支出。再以person类派生出教师类teacher和大学生类collegestudent其中: 教师:工资支出=基本工资+授课时数*30 大学生:奖学金支出

将人员类定义为抽象类,pay为抽象方法,设计程序实现多态性。

public abstract class Person {

public abstract void pay(int a,int b); public abstract void pay(); }

public class CollegeStudent { int award;

public void pay(int w){ this.award=w;

System.out.println(\的奖学金支出是:\ } }

public class Teacher extends Person{ int wage; int time; int p;

public void pay(int w,int t){ this.wage=w; this.time=t; p=wage+time*30;

System.out.println(\的工资支出是:\

}

@Override

public void pay() {

// TODO Auto-generated method stub } }

public class Test2 {

public static void main(String[]args){ Teacher a=new Teacher();

CollegeStudent b=new CollegeStudent(); a.pay(5000,50);

b.pay(3000); }

}

1. 将1~100之间的所有正整数在放在一个List

集合中,并将集合中索引位置是10的对象从集合中移除。

import java.util.*; public class Test {

public static void main(String[] args) {

List list1 = new ArrayList(); for (int i = 1; i <= 100; i++) {

list1.add(i); }

list1.remove(10); Iterator it = list1.iterator();

while (it.hasNext()) {

System.out.println(it.next());

} } }

2.分别向Set集合以及List集合中添加“A”“、a”、“c”、”C”、”a”5个元素,观察重复值能否在List集合以及Set集中成功添加。

import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Test2 {

public static void main(String[] args) { Set set=new HashSet(); set.add(\ set.add(\ set.add(\ set.add(\ set.add(\

System.out.println(set); List list1=new ArrayList(); list1.add(\ list1.add(\ list1.add(\ list1.add(\ list1.add(\

System.out.println(list1) }

3. (List)已知有一个Worker 类如下:

public class Worker {

private int age; private String name; private double salary; public Worker (){}

public Worker (String name, int age, double salary){

this.name = name; this.age = age;

this.salary = salary; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public double getSalary(){ return salary; }

public void setSalary(double salary){ this.salary = salary; }

public void work(){

System.out.println(name + “ work”); } }

完成下面的要求

1) 创建一个List,在List 中增加三个工人,基本信息如下: 姓名 年龄 工资 zhang3 18 3000 li4 25 3500 wang5 22 3200

2) 在li4 之前插入一个工人,信息为:姓名:zhao6,年龄:24,工资3300 3) 删除wang5 的信息

4) 利用for 循环遍历,打印List 中所有工人的信息

5) 利用迭代遍历,对List 中所有的工人调用work 方法。 package z3; public class Worker { private int age; private String name; private double salary;

public Worker (){ }

public Worker (String name, int age,

double salary){

this.name = name; this.age = age;

this.salary = salary; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public double getSalary(){ return salary; }

public void setSalary(double salary){ this.salary = salary; }

public void work(){

System.out.println(name+\ } }

package z3;

import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Test3 {

public static void main(String[] args) { Worker w1=new Worker(\ Worker w2=new Worker(\ Worker w3=new Worker(\ Worker w4=new Worker(\ List list1=new ArrayList(); list1.add(w1); list1.add(w2); list1.add(w3); list1.add(1,w4);

list1.remove(w3);

for(int i=0;i

Worker wer=(Worker)list1.get(i);;

System.out.println(wer.getName()+\getAge()+\ }

Iterator it=list1.iterator(); while(it.hasNext()){

Worker w=(Worker) it.next(); w.work(); } }

}

(Map)利用Map,完成下面的功能:

从命令行读入一个字符串,表示一个年份,输出该年的世界杯冠军是哪支球队。如果该

年没有举办世界杯,则输出:没有举办世界杯。package z1;

import java.util.HashMap; import java.util.Scanner; public class Test1 {

public static void main(String[]args){ HashMap hm=new HashMap(); hm.put(\意大利\ hm.put(\巴西\ hm.put(\法国\ hm.put(\巴西\ hm.put(\德国\ hm.put(\阿根廷\ hm.put(\意大利\ hm.put(\阿根廷\ hm.put(\德国\ hm.put(\巴西\ hm.put(\英格兰\ hm.put(\巴西\ hm.put(\巴西\ hm.put(\德国\ hm.put(\乌拉圭\ hm.put(\意大利\ hm.put(\意大利\ hm.put(\乌拉圭\

System.out.println(\请输入一个年份:\ Scanner sc=new Scanner(System.in); String y=sc.nextLine(); System.out.print(y);

if(hm.containsKey(y)){

System.out.println(hm.get(y)); } else{

System.out.println(\没有举办世界杯\ } } }

完成下列要求:

1) 使用一个Map,以老师的名字作为键,以老师教授的课程名作为值,表示上述 课程安排。

2) 增加了一位新老师Allen 教JDBC 3) Lucy 改为教CoreJava

4) 遍历Map,输出所有的老师及老师教授的课程 5) *利用Map,输出所有教JSP 的老师。 package z2; import java.util.*; public class Test2{

public static void main(String[] args){ HashMap hm=new HashMap(); hm.put(\ hm.put(\ hm.put(\ hm.put(\ hm.put(\ hm.put(\ hm.put(\ hm.put(\

System.out.println(\添加后的结果是:

\

System.out.println(hm); hm.put(\

System.out.println(\替换后的结果是:

\

System.out.println(hm); Iterator it

=hm.entrySet().iterator(); while (it.hasNext()) {

System.out.println(it.next()); }

Set set=hm.keySet(); for(Object str:set){

if(hm.get(str).equals(\

System.out.println(\教

JSP的老师有:\

} } } }

(泛型)使用泛型,改写第5 题 import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; import java.util.Set; public class Test3 {

public static void main(String[] args) { Set setWorker=new

HashSet();

Scanner sc=new Scanner(System.in); String str=sc.nextLine(); Iterator it

=setWorker.iterator(); while (it.hasNext()) { if (it.equals(str)) {

System.out.println(\放入HashSet

中时不会出现重复元素\ } } } }

Set)有如下两个类(只写了类的属性,请自行添加相

应的构造方法和get/set 方法)

要求,完善Worker 和Address 类,使得Worker 对象

能够正确放入HashSet 中:即将

Worker 放入HashSet 中时不会出现重复元素。并编写相应测试代码。 package z3;

public class Address {

private String addressName; private String zipCode;

public void address(String aN,String zC){ this.addressName=aN; this.zipCode=zC; }

public String getAddressName() { return addressName; }

public void setAddressName(String addressName) { this.addressName = addressName; }

public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; }

public class Worker{ private String name; private int age;

private double salary; private Address address;

public void worker(String n,int a,double

s,Address ad){ this.name=n; this.age=a; this.salary=s; this.address=ad; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }

public double getSalary() { return salary; }

public void setSalary(double salary) { this.salary = salary; }

public Address getAddress() { return address; }

public void setAddress(Address address) { this.address = address; } } }

编写一个异常类MyException,再编写一个类Student,该类有一个产生异常的方法speak(int m)。 要求参数m的值大于1000时,方法抛出一个MyException对象。最后编写主类,在方法中创新Student对象,让该对象调用speak()方法。

public class MyException extends Exception{ public MyException(){ this(\发生异常了\ }

public MyException(String message) { super(message); } }

public class Student {

public void speak(int m)throws MyException{ if(m>1000){

throw new MyException(\发生了异常\ } } }

public class Test1 {

public static void main(String[] args) { Student s=new Student();

// MyException me=new MyException(); int m; try{

s.speak(1200);

}catch(MyException e){

System.out.println(\出现了异常\ } } }

q创建类Computer,该类中有一个计算两个数的最大公约数的方法。如果向该方法传递负整数,该方法就会抛出自定义异常。 package a2;

public class MyException extends Exception { private String reason;

public MyException(int x,int y){ reason=\出现异常\ }

public String getReason(){ return reason; } }

package a2; import java.util.Scanner;

public class Computer {

int m,n;

public void zdgys(int x,int y)throws MyException{

if(x<=0||y<=0)

throw new MyException(x,y); else{ if(x

int r=x%y; while(r!=0){ x=y; y=r; r=x%y; }

System.out.println(\最大公约数是:\

} }

public static void main(String[] args) {

int result =0;

Computer c=new Computer(); try{

System.out.println(\请输入两个数:\

Scanner s=new Scanner(System.in); int x=s.nextInt(); int y=s.nextInt();

c.zdgys(x, y);

}catch(MyException e){

System.out.println(e.getReason()); } } }

q自定义类Sanj,其中有成员 x,y,z,作为三边长,构造方法Sanj(a,b,c)分别给x,y,z赋值,方法求面积getArea和显示三角形信息(三个边长)showInfo,这2个方法中当三条边不能构成一个三角形时要抛出自定

义异常NotSanjiaoException,否则显示正确信息。在另外一个类中的主方法中构造一个Sanj对象(三边为命令行输入的三个整数),显示三角形信息和面积,要求捕获异常。 package a3;

public class NotSanjiaoException extends Exception{ String reason;

public NotSanjiaoException(int a,int b,int c){ reason=\三条边不能构成三角形\}

public String getReason(){ return reason; } }

package a3;

public class Sanj { int x,y,z;

public Sanj(int a,int b,int c) {

this.x=a; this.y=b; this.z=c; }

public void getArea(){ int sum=x+y+z; double p=sum/2;

double s=Math.sqrt(p*(p-x)*(p-y)*(p-z)); System.out.println(\三角形的面积是:\ }

public void showInfo(){

System.out.println(\三角形的边长是:\ } }

package a3;

import java.util.Scanner; public class Test3 {

public static void main(String[] args) { int x,y,z ; System.out.println(\请输入三角形的边长\ Scanner sc=new Scanner(System.in); x=sc.nextInt(); y=sc.nextInt(); z=sc.nextInt(); try{

if(x+y<=z||x+z<=y||y+z<=x){

throw new NotSanjiaoException (x,y,z); } else{

Sanj sj1=new Sanj(x,y,z);

sj1.getArea(); sj1.showInfo(); }

}catch(NotSanjiaoException e){

System.out.println(e.getReason()); } } }

q写一个方法void sanjiao(int a,int b,int c),判断三个参数是否能构成一个三角形,如果不能则抛出异常IllegalArgumentException,显示异常信息a,b,c+”不能构成三角形”,如果可以构成则显示三角形三个边长,在主方法中得到命令行输入的三个整数,调用此方法,并捕获异常。

public class IllegalArgumentException extends Exception{

String reason;

public IllegalArgumentException(int a,int b,int c){

reason=\异常信息a,b,c+”不能构成三角形\ }

public String getReason(){ return reason; } }

package a4;

import java.util.Scanner;

public class Triangle { //int a,b,c;

public static void sanjiao(int a,int b,int c)throws IllegalArgumentException{

// a=this.a; // b=this.b; // c=this.c;

if(a+b<=c||a+c<=b||b+c<=a){

throw new IllegalArgumentException(a, b,c);

} else{

System.out.println(a+\能构成三角形\ } }

public static void main(String[] args) {

System.out.println(\请输入三条边:\ Scanner sc=new Scanner(System.in); int a=sc.nextInt(); int b=sc.nextInt(); int c=sc.nextInt(); try {

sanjiao(a,b,c);

} catch (IllegalArgumentException e) { System.out.println(e.getReason()); }

} }

1. 程序功能:将键盘上输入的字符在屏幕上显示出来。

package z1;

import java.io.BufferedReader; import java.io.IOException;

import java.io.InputStreamReader; public class Test1 {

public static void main(String[] args) { BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

System.out.println(\请输入一行数据:\ try { System.out.println(\您输入的是:\

} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

}

}

2. 程序功能:将保存在本地机当前文件夹中的

LX5_1.HTML 文本文件的内容在屏幕上显示出来,然后将其另存为LX5_1.txt 文件。

package z2;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;

import java.io.OutputStreamWriter; public class Test2 { public static void main(String[] args) throws IOException {

FileReader in = new FileReader(\

BufferedReader br = new BufferedReader(in);

FileWriter out = new FileWriter(\

String str; while ((str = br.readLine()) != null) {

System.out.println(str); out.write(str + \ } in.close(); out.close(); } }

3. 编写一个java课的成绩统计程序,从键盘输入学生

姓名和成绩,程序按成绩排出名次,并统计出最高分、最低分、平均分。学生的个数在程序运行前是未知数。

package z3;

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException;

import java.io.InputStreamReader; import java.nio.Buffer; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Test3{

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

System.out.println(\请输入学生数\

int s=sc.nextInt();

int[] a=new int[s]; System.out.println(\请输入学生成绩以逗号隔开\

BufferedReader br=new BufferedReader(new

InputStreamReader(System.in));

try { String str=br.readLine();

String[] s1=str.split(\

for(int i=0;i

a[i]=Integer.parseInt(s1[i]);

} } catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} int max=0; int min=100; int sum=0; for (int j = 0; j < a.length; j++) {

for (int i = j+1; i < a.length; i++) {

if(a[j]

System.out.print(a[j]); }

}

for(int j=0;j

if(a[j]>max){

max=a[j];

}

if(a[j]

min=a[j]; } sum+=a[j]; } System.out.println(\最高分数:\

System.out.println(\最低数\

System.out.println(\平均分数:\

} }

4.编写一个程序,类名为WordCount,统计单词“hello”在一篇英文文章(保存在文件

article.txt)中出现的次数,要求统计时忽略单词的大小写,统计结果在屏幕上打印出来的格式为:单词***在文章***中出现的次数为:10。提示:下面是String类中的几个方法:

public int indexOf(String str) //返回指定子字符串在此字符串中第一次出现处的索引。

public int indexOf(String str,int fromIndex) //从指定的索引开始,返回指定子字符串在此字符串中第一次出现处的索引。

public String

toUpperCase() // String 中的所有字符都转换为大写

public String toLowerCase

() // String 中的所有字符都转换为小写

package z4;

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException;

public class HelloCount { int getHelloCount(String aritleName,String hello) { int count=0; String sentense; try{

BufferedReader br=new BufferedReader(new

FileReader(aritleName));

hello=hello.toLowerCase();

while((sentense=br.readLine())!=null){

System.out.println(sentense);

sentense=sentense.toLowerCase(); int

index=sentense.indexOf(hello); while(index>=0){ count++;

index=sentense.indexOf(hello,index+hello.length()); } }

}catch (Exception e) {

System.out.println(\文件目录错1.误\ }

return count; }

public static void main(String[] args) throws IOException {

String article=\ String hello=\

HelloCount h=new HelloCount();

System.out.println(\单词\在文章中出现的次数:

\ } } 4. 编写一个程序WriteLog.java实现如下功能:从键

盘输入若行文字(可能包含中文),当最后一行输入quit#时,退出程序且将输入内容除quit#外全部存入文件c:\\log.txt中

package z5;

import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Scanner; public class WriteLog { private static PrintWriter out; public static void main(String[] args) { try { out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(

\ } catch (FileNotFoundException e) { e.printStackTrace(); } Scanner in = new Scanner(System.in); String line =null; while (!\in.nextLine())) {

out.println(line); } out.flush(); out.close(); } }

编写程序:使用字符输入、输出流读取文件,将一段文字加密后存入文件,然后再读取,并将加密前与加密后的文件输出。

package IOTest;

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File;

import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner;

public class Jiami {

public static void main(String[] args) throws IOException {

BufferedReader br=new BufferedReader(new FileReader(new File(\

BufferedWriter bw=new BufferedWriter(new } FileWriter(new File(\ out.flush();

Scanner scan=new Scanner(System.in); out.close(); String str=scan.nextLine(); } char []c=str.toCharArray(); } System.out.println(); 3.编写程序:输入两个正整数m和n,求其最大公约数和最小 char []w=new char[c.length]; 公倍数。 for (int i = 0; i

} deff cd = new deff(); br.close(); m = cd.deff(a, b); } int n = a * b / m; } System.out.println(\最大公约数: \2. 编写程序:实现当用户输入姓名和密码时,将每一个姓名 System.out.println(\最小公倍数: \

和密码加在文件中,如果用户输入done,就结束程序。 }

package z5; } import java.io.FileNotFoundException; class deff { import java.io.FileOutputStream; public int deff(int x, int y) { import java.io.OutputStreamWriter; int t; import java.io.PrintWriter; if (x < y) { import java.util.Scanner; t = x; x = y; public class WriteLog { y = t; private static PrintWriter out; } while (y != 0) { public static void main(String[] args) { if (x == y) try { return x; out = new PrintWriter(new else { OutputStreamWriter(new FileOutputStream( int k = x % y;

\ x = y; } catch (FileNotFoundException e) { y = k; e.printStackTrace(); } } } System.out.println(\请输入用户名和密码, return x; 中间用逗号隔开。结束输入时输入‘done’\ }

Scanner in = new Scanner(System.in); } String line =null; while (!\5. 编写程序:输入一行字符,分别统计出其中英文字母、in.nextLine())) { 空格、数字和其它字符的个数。

out.println(line);

package z5;

import java.util.Scanner; public class T3 {

public static void main(String[] args) { System.out.println(\请输入一个字符串\ Scanner sc=new Scanner(System.in); String str =sc.nextLine(); char ch [] = new char[str.length()]; ch=str.toCharArray(); int eng=0 ,kong=0,shu=0,qi=0; for (int i = 0; i < ch.length; i++) { if (65ch[i] && ch[i]>122&& ch[i]!=32) { qi++; } } System.out.println(\英文字母有\ System.out.println(\空格有\ System.out.println(\数字有\ System.out.println(\其他字符有\}

}

一、数据库综合应用练习1: 1.在数据库中建立一个表,表名为student,其结构为:学号(num)、姓名(name)、性别(sex)、年龄(age)、成绩(score)

2.在student表中输入四条记录(自己设计具体数据内容)

3.在屏幕上显示表中的所有内容 4.增加两条学生记录: 05,李芳,女,20,76 06,张良,男,19,70 5.将每人的年龄增加2岁 6.删除成绩不及格的学生记录 7.显示最终表格的内容 package a1;

import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JDBCUtils {

private static String url =

\tudent\

private static String driver =

\ private static String user = \

private static String password =\ static{ try{

Class.forName(driver);

}catch(ClassNotFoundException e){

System.out.println(\找不到驱动程序类 ,加载驱动失败!\

e.printStackTrace() ; } }

public static Connection getConnection() throws SQLException{

return DriverManager.getConnection(url, user, password); }

public static void release(Connection conn,Statement st,ResultSet rs){ if(rs!=null){ try{

rs.close();

}catch (Exception e) { e.printStackTrace(); }finally{

if(st!=null){ try{

st.close();

}catch (Exception e) { e.printStackTrace(); }finally{

if(conn!=null){ try{

conn.close(); }catch (Exception e) {

e.printStackTrace();

}finally{ }

} } } }

}

}

}

package a1;

import java.sql.*;

public class JdbcXianshi {

public static void main(String[] args) { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn =JDBCUtils.getConnection(); String str=\order by num\

st = conn.prepareStatement(str); rs = st.executeQuery(); while (rs.next()) { System.out.print(rs.getString(\

System.out.print(rs.getString(\

System.out.print(rs.getString(\

System.out.print(rs.getString(\

System.out.println(rs.getString(\

} } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { JDBCUtils.release(conn, st, rs); } } }

package a1;

import java.sql.Connection;

import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;

public class Add {

public static void main(String[] args) { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn=JDBCUtils.getConnection(); String str=\values(?,?,?,?,?)\

st=conn.prepareStatement(str); st.setString(1, \ st.setString(2, \李芳\ st.setString(3, \女\ st.setInt(4, 20); st.setInt(5, 76); st.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JDBCUtils.release(conn, st, rs); } } }

package a1;

import java.sql.Connection;

import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;

public class AddAge { public static void main(String[] args) { Connection con=null; PreparedStatement st=null; ResultSet rs=null; try { con=JDBCUtils.getConnection(); String str=\age=age+2\

st=con.prepareStatement(str); st.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block

e.printStackTrace();

}finally{

JDBCUtils.release(con, st, rs); }

}

}

package a1;

import java.sql.Connection;

import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Delete {

public static void main(String[] args) { Connection con=null;

PreparedStatement st=null; ResultSet rs=null; try {

con=JDBCUtils.getConnection();

String str=\from student where score<60 \

st=con.prepareStatement(str); st.executeUpdate(); } catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace(); }finally{

JDBCUtils.release(con, st, rs); } } }

package a1;

import java.sql.Connection;

import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class XianShi2 {

public static void main(String[] args) { Connection conn = null;

PreparedStatement st = null; ResultSet rs = null; try {

conn=JDBCUtils.getConnection(); String str=\ st=conn.prepareStatement(str); rs=st.executeQuery(); while(rs.next()){

System.out.print(rs.getString(\

System.out.print(rs.getString(\

System.out.print(rs.getString(\

System.out.print(rs.getString(\

System.out.println(rs.getString(\ }

} catch (SQLException e) {

// TODO Auto-generated catch block e.printStackTrace(); }finally{

JDBCUtils.release(conn, st, rs); } }

二、数据库综合应用练习2: 用java新建一个表格,表名为table,结构为:id int,name char,age int,score int

并为table表格增加三条记录,(具体数据自己设计)显示table表格中的所有信息

提示:增加表 Sql=“create table student(id int,name char,age int,score float)”;

删除表 sql=“drop table student”;

package sdjtu.hyJDBCTest; public class StudentBean { private String num; private String name; private String sex; private int age; private float score; public String getNum() { return num; }

public void setNum(String num) { this.num = num; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public String getSex() { return sex; }

public void setSex(String sex) { this.sex = sex; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }

public float getScore() { return score; }

public void setScore(float score) { this.score = score; } }

package sdjtu.hyJDBCTest; import java.sql.Connection;

import java.sql.PreparedStatement; import java.sql.ResultSet; import sdjtu.hyJDBC.JDBCUtils; public class JdbcAdd {

public void add(StudentBean te) {

// TODO Auto-generated method stub Connection conn = null;

PreparedStatement st = null; ResultSet rs = null; try {

conn = JDBCUtils.getConnection(); String sql = \ + \ st = conn.prepareStatement(sql); st.setString(1, te.getNum()); st.setString(2, te.getName()); st.setString(3, te.getSex()); st.setInt(4, te.getAge()); st.setFloat(5, te.getScore()); st.execute();

} catch (Exception e) { e.printStackTrace(); } finally {

JDBCUtils.release(conn, st, rs); } }

public static void main(String[] args) { JdbcAdd jd=new JdbcAdd();

StudentBean te = new StudentBean(); te.setNum(\ te.setName(\李芳\ te.setSex(\女\ te.setAge(19); te.setScore(70); jd.add(te); } }

package sdjtu.hyJDBCTest; import java.sql.Connection;

import java.sql.PreparedStatement; import java.sql.ResultSet; public class JdbcDelete {

public static void main(String[] args) { Connection conn = null;

PreparedStatement st = null; ResultSet rs = null; try {

conn =

sdjtu.hyJDBC.JDBCUtils.getConnection();

String sql = \score<60\

st = conn.prepareStatement(sql); st.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally {

sdjtu.hyJDBC.JDBCUtils.release(conn, st, rs); }

JdbcXianshi jd=new JdbcXianshi(); jd.qureyAll(); } }

package sdjtu.hyJDBCTest; import java.sql.Connection;

import java.sql.PreparedStatement; import java.sql.ResultSet; public class JdbcUpdate {

public static void main(String[] args) { Connection conn = null;

PreparedStatement st = null; ResultSet rs = null; try {

conn =

sdjtu.hyJDBC.JDBCUtils.getConnection(); String sql = \age=age+2\

st = conn.prepareStatement(sql); st.executeUpdate(); } catch (Exception e) {

e.printStackTrace(); } finally {

sdjtu.hyJDBC.JDBCUtils.release(conn, st, rs); } } }

package sdjtu.hyJDBCTest; import java.sql.Connection;

import java.sql.PreparedStatement; import java.sql.ResultSet; import sdjtu.hyJDBC.JDBCUtils; public class JdbcXianshi { public void qureyAll(){ Connection conn = null;

PreparedStatement st = null; ResultSet rs = null; try {

conn =

sdjtu.hyJDBC.JDBCUtils.getConnection();

String sql = \order by num\

st = conn.prepareStatement(sql); rs = st.executeQuery(); while (rs.next()) {

System.out.print(\学号\

System.out.print(\姓名\

System.out.print(\性别\

System.out.print(\年龄\

System.out.print(\成绩\

System.out.println(); }

} catch (Exception e) { e.printStackTrace(); } finally {

JDBCUtils.release(conn, st, rs); } }

public static void main(String[] args) { JdbcXianshi jd= new JdbcXianshi(); jd.qureyAll(); } }

本文来源:https://www.bwwdw.com/article/ibrx.html

Top