Java清览题库实验 (实验二 ~ 实验六)

文章目录

  • 实验二 基本数据类型、控制语句的应用 (5)
    • 两个数之间的经典问题
    • 谷值
    • 找出n以内的所有”孪生数”.
    • 完数
    • 完数(三个)
  • 实验三 类与对象 (3)
    • 机动车
    • 家中的电视
    • 共饮同井水
  • 实验四 继承与接口 (6)
    • 中国人、北京人和美国人
    • 银行计算利息
    • 公司支出的总薪水
    • 评价成绩
    • 货车的装载量
    • 小狗的状态
  • 实验五 内部类与异常类 (1)
    • 检查危险品
  • 实验六 常用实用类 (6)
    • 截取字符串
    • 子串出现频率
    • 统计指定字符的次数
    • 使用Scanner类
    • 替换错别字
    • 处理大整数

实验二 基本数据类型、控制语句的应用 (5)

两个数之间的经典问题

求指定两个数的最大公约数和最小公倍数

import java.util.Scanner;
public class Main{
  	public static void main(String[] args) {
		int a = 0;
		int b = 0;
		Scanner scanner = new Scanner(System.in);
			a = scanner.nextInt();
			b = scanner.nextInt();
		int max = max(a,b);
	  long min = min(a,b);
		System.out.println(max);
		System.out.println(min);
  }

	// 计算最大公约数
	private static int max(int a, int b) {  
		int m = a < b ? a : b;   //找到两个数的最小值
		for(int i = m; i >= 1; i--) {
			if(a % i == 0 && b % i == 0) {
				return i;
			}
		}
		return 0; 
	}
  
  // 计算最小公倍数
  private static long min(int a, int b) {
		int m = a > b ? a :b;  //找到两个数的最大值
		for(long i = m; ; i += m) {
			if(i % a == 0 && i % b == 0) {
				return i;
			}
		}
	}
}

谷值

输入数组长度n,并输入n个数,统计数组中的谷值个数。(一个数若小于相邻的数则称为数组的谷值,若没有相邻的值也算谷值)

import java.util.Scanner;
public class Main{
  	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] a = new int[n];
		for(int i = 0; i < n; i++) {
			a[i] = sc.nextInt();
		}//谷值个数
		int sum = 0;
		for(int i = 0; i < n; i++) {
			if (n == 1) {
				//只有一个值,谷值个数为1
				sum++;
			} else if (i == 0) {
				//第一个只需和后面的比较
				if (a[i] < a[i + 1]) {
					//这里出现谷值的话,下一个点就不可能是谷值,可以直接跳过
					sum++;
					i++;
				}
			}else if (i == n - 1) {	//最后一个只需和前面的比较
				if (a[i] < a[i - 1]) {
					//因为已经到了最后一个,直接写不写i++;都无所谓
					sum++;			
				}
			}else {
				if (a[i] < a[i - 1] && a[i] < a[i + 1]) {
					//这里出现谷值的话,下一个点就不可能是谷值,可以直接跳过
					sum++;			
					i++;
				}
			}
		}
		System.out.println(sum);
    }
}

找出n以内的所有”孪生数”.

如果两个素数之差为2,这样的两个素数就叫作”孪生数”,
找出n和m之间的的所有”孪生数”.
每输出一组孪生数,均保持输出格式:(孪生数为:m,n)

import java.util.Scanner;
public class Main{
       public static void main(String[] args) {
        int n=0;
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();

        int count=0;
        int[] a=new int[n];
        boolean flag;
        for(int i=0;i<n;i++){
            flag=true;//注意每一轮初始flag都为true,声明时不要赋值,否则上一轮循环的flag值对新一轮的值有影响
            //判断是否是素数
            for (int j=2;j<=i/2;j++){
                if(i%j==0){
                    flag=false;
                    break;
                }
            }
            //如果是素数就把素数存在数组里
            if(flag==true){
                a[count]=i;
                count++;
            }
        }
        //判断相邻素数之差是否为2,是就打印显示
        for(int i=0;i<count-1;i++){
            if(a[i+1]-a[i]==2){
                System.out.println("(孪生数为:"+a[i]+","+a[i+1]+")");
            }
        }
    }
}

完数

一个数如果恰好等于它的因子之和,这个数就称为”完数”。例如6=1+2+3.编程找出1000以内的所有完数。
输入:无
输出:i1 i2 i3……

public class Main {
    public static void main(String[] args) {  
        // 遍历1到1000之间的所有数  
        for (int i = 1; i <= 1000; i++) {  
            // 判断该数是否为完数  
            if (isPerfect(i)) {  
                // 如果是完数,则输出该数及其因子之和  
                System.out.print(getFactors(i)+" ");  
            }  
        }  
    }  
  
    // 判断一个数是否为完数  
    public static boolean isPerfect(int number) {  
        int sum = 0;  
        for (int i = 1; i <= number / 2; i++) {  
            if (number % i == 0) {  
                sum += i;  
            }  
        }  
        return sum == number;  
    }  
  
    // 获取一个数的因子之和  
    public static int getFactors(int number) {  
        int sum = 0;  
        for (int i = 1; i <= number / 2; i++) {  
            if (number % i == 0) {  
                sum += i;  
            }  
        }  
        return sum;  
    }  
}

完数(三个)

一个数如果恰好等于它的因子之和,这个数就称为”完数”。例如6=1+2+3.编程找出1000以内的所有完数。
输入:无
输出:i1 i2 i3……


public class Main {  
    public static void main(String[] args) {  
        // 遍历1到1000之间的所有数  
        for (int i = 1; i <= 1000; i++) {  
            // 判断该数是否为完数  
            if (isPerfect(i)) {  
                // 如果是完数,则输出该数及其因子之和  
                System.out.print(getFactors(i)+"  ");  
            }  
        }  
    }  
  
    // 判断一个数是否为完数  
    public static boolean isPerfect(int number) {  
        int sum = 0;  
        for (int i = 1; i <= number / 2; i++) {  
            if (number % i == 0) {  
                sum += i;  
            }  
        }  
        return sum == number;  
    }  
  
    // 获取一个数的因子之和  
    public static int getFactors(int number) {  
        int sum = 0;  
        for (int i = 1; i <= number / 2; i++) {  
            if (number % i == 0) {  
                sum += i;  
            }  
        }  
        return sum;  
    }  
}

实验三 类与对象 (3)

机动车

编写一个Java应用程序,该程序中有两个类,即Vehicle(用于刻画机动车)和Main(主类)。具体要求如下:
(1)Vehicle类有一个double类型的变量speed,用于刻画机动车的速度,有一个int类型变量power,用于刻画机动车的功率。在类中定义了speedUp()方法,体现机动车有加速功能;定义了speedDown()方法,体现机动车有减速功能;定义了setPower(int p)方法,用于设置机动车的功率;定义了getPower()方法,用于获取机动车的功率。
(2)在主类Main的main()方法中用Vehicle类创建对象,并让该对象调用方法设置功率,演示加速和减速功能。


public class Main{
  	public static void main(String[] args) {
        Vehicle v1 = new Vehicle();
		Vehicle v2 = new Vehicle();
		v1.setPower(128);
		v2.setPower(76);
		System.out.println("car1的功率是:"+v1.getPower());
		System.out.println("car2的功率是:"+v2.getPower());
		v1.speedUp(80);
		v2.speedUp(80);
		System.out.println("car1目前的速度:"+v1.getSpeed());
		System.out.println("car2目前的速度:"+v2.getSpeed());
		v1.speedDown(10);
		v2.speedDown(20);
		System.out.println("car1目前的速度:"+v1.getSpeed());
		System.out.println("car2目前的速度:"+v2.getSpeed());
    }
}

class Vehicle {
	double speed;   //机动车的速度
	int power;    //机动车的功率
	void speedUp(int s){
			if (s <0)
		System.out.print("error");
			else
		speed=speed+s;
	}
	//减速功能
	void speedDown(int d){
		if(d > speed)
			speed = 0;
		else
			speed -= d;
	}
	void setPower(int p){
		power = p;
	}
	//获取机动车的功率
	int getPower(){
		return power;
	}
	double getSpeed(){
		return speed;
	}
}

家中的电视

编写一个Java应用程序,模拟家庭买一台电视,即家庭将电视作为自己的一个成员,通过调用一个方法将某台电视的引用传递给自己的电视成员。具体要求如下:
(1)有TV.java、Family.java和Main.java3个源文件,其中TV.java中的TV类负责创建“电视”对象,Family.java中的Family类负责创建“家庭”对象,Main.java是主类。
(2)在主类的main()方法中首先使用TV类创建一个对象haierTV,然后使用Family类再创建一个对象zhangSanFamily,并将先前TV类的实例haierTV的引用传递给zhangSanFamily对象的成员变量homeTV。


class TV {
	int channel;	
	void setChannel(int m) {
		if(m>1) {
			channel = m;
		}
	}
	int getChannel() {
		return channel;
	}
	void showProgram() {
		switch(channel) {
		case 1:
			System.out.println("综合频道");
			break;
		case 2:
			System.out.println("经济频道");
			break;
		case 3:
			System.out.println("文艺频道");
			break;
		case 4:
			System.out.println("国际频道");
			break;
		case 5:
			System.out.println("体育频道");
			break;
		default:
			System.out.println("不能收看"+channel+"频道");
		}
	}
}

 class Family {
	TV homeTV;
	void buyTV(TV tv) {
		//将参数tv赋值给homeTV
		homeTV = tv;
	}
	void remoteControl(int m) {
		homeTV.setChannel(m);
	}
	void seeTV() {
		homeTV.showProgram();//homeTV调用showProgram()方法
	}
}


public class Main {
	public static void main(String[] args) {
		TV haierTV = new TV();
		//haierTV调用setChannel(int m),并向参数m传递5
		haierTV.setChannel(5);		
		System.out.println("haierTV的频道是"+haierTV.getChannel());
		Family zhangSanFamily = new Family();
		//zhangSanFamily调用void buyTV(TV tv)方法,并将haierTV传递给参数TV
		zhangSanFamily.buyTV(haierTV);		
		System.out.println("zhangSanFamily开始看电视节目");
		zhangSanFamily.seeTV();
		int m=2;
		System.out.println("hangSanFamily将电视更换到"+m+"频道");
		zhangSanFamily.remoteControl(m);
		System.out.println("haierTV的频道是"+haierTV.getChannel());
		System.out.println("hangSanFamily再看电视节目");
		zhangSanFamily.seeTV();
	}
}

共饮同井水

编写程序模式两个村庄共用同一口井水。编写一个Village类,该类有一个静态的int型成员变量waterAmout,用于模式井水的水量。在主类的Main的main()方法中创建两个村庄,一个村庄改变了waterAmount的值,另一个村庄查看waterAmount的值。


class Village {
    static int waterAmount;   //模拟水井的水量
    int peopleNumber;         //村庄的人数
    String name;              //村庄的名字
    Village(String s) {
        name = s;
    }
    static void setWaterAmount(int m) {
       if(m>0)
         waterAmount = m;
    } 
    void drinkWater(int n){
       if( waterAmount-n>=0) {
         waterAmount = waterAmount-n;
         System.out.println(name+"喝了"+n+"升水");
       }
       else
         waterAmount = 0;
    }
	public static int waterAmount() {
		// TODO Auto-generated method stub
	   return waterAmount;
	}  
    static int lookWaterAmount() {
       return waterAmount;
    }
    void setPeopleNumber(int n) {
       peopleNumber = n;
    } 
    int getPeopleNumber() {
       return peopleNumber;
    } 
}

public class Main {
    public static void main(String args[]) {
       //用类名调用setWaterAmount(int m),并向参数传值200
       Village.setWaterAmount(200);
       //用Village类的类名访问waterAmount
       int leftWater =Village.waterAmount(); 
       System.out.println("水井中有 "+leftWater+" 升水");
       Village zhaozhuang,majiahezi;
       zhaozhuang = new Village("赵庄");
       majiahezi = new Village("马家河子");
       zhaozhuang.setPeopleNumber(80);
       majiahezi.setPeopleNumber(120);
       //fengZhuang调用drinkWater(int n),并向参数传值50
       zhaozhuang.drinkWater(50);
       //zhaozhuang调用lookWaterAmount()方法
       leftWater = majiahezi.lookWaterAmount(); 
       String name=majiahezi.name;
       System.out.println(name+"发现水井中有 "+leftWater+" 升水");
       majiahezi.drinkWater(100);
       //fengZhuang调用lookWaterAmount()方法
       leftWater = zhaozhuang.lookWaterAmount(); 
       name=zhaozhuang.name; 
       System.out.println(name+"发现水井中有 "+leftWater+" 升水");
       int peopleNumber = zhaozhuang.getPeopleNumber(); 
       System.out.println("赵庄的人口:"+peopleNumber);
       peopleNumber = majiahezi.getPeopleNumber(); 
       System.out.println("马家河子的人口:"+peopleNumber);
    }
}

实验四 继承与接口 (6)

中国人、北京人和美国人

编写程序模拟中国人、美国人是人,北京人是中国人。除主类外,该程序还有People、ChinaPeople、AmericanPeople和BeijingPeople4个类。要求如下:
(1)People类有权限是protected的double型成员变量height和weight,以及public void speakHello()、public void averageHeight()和public void averageWeight()方法。
(2)ChinaPeople类是People的子类,新增了public void chinaGongfu()方法,要求Chinese重写父类的public void speakHello()、public void averageHeight()和public void averageWeight()方法。
(3)AmericanPeople类是People的子类,新增了public void americanBoxing()方法,要求American重写父类的public void speakHello()、public void averageHeight()和public void averageWeight()方法。
(4)BeijingPeople类是ChinaPeople的子类,新增了public void beijingOpera()方法,要求Beijingman重写父类的public void speakHello()、public void averageHeight()和public void averageWeight()方法。

public class Main {
	public static void main(String[] args) {
	Chinese chinese = new Chinese();
  American american = new American();
	Beijingman beijingman = new Beijingman(); 
  chinese.speakHello();
	american.speakHello();
	chinese.speakHello();
	chinese.averageHeight();
	american.averageHeight();
	beijingman.averageHeight();
	chinese.averageWeight();
	american.averageWeight();
	beijingman.averageWeight();
	chinese.chinaGongfu();
	american.americanBoxing();
	beijingman.beijingOpera();
	chinese.chinaGongfu();	
	}
}
 
class People {
	protected double height;
	protected double weight;
	
	public void speakHello() {
		System.out.println("yayaya");
	}
	
	public void averageHeight() {
		height = 173;
		System.out.println();
	}
	
	public void averageWeight() {
		weight = 70;
		System.out.println();
	}
	
}
 
class Chinese extends People {
	
	public void chinaGongfu() {
		System.out.println("坐如钟,站如松,睡如弓");
	}
	
	public void speakHello() {
		System.out.println("您好");
	}
	
	public void averageHeight() {
		height = 168.78;
		System.out.println("中国人的平均身高:"+height+" 厘米");
	}
	
	public void averageWeight() {
		weight = 65;
		System.out.println("中国人的平均体重:" + weight + "千克");
	}
	
}
 
class American extends People {
	public void americanBoxing() {
		System.out.println("直拳、钩拳、组合拳");
	}
	
	public void speakHello() {
		System.out.println("How do you do");
	}
	
	public void averageHeight() {
		height = 176;
		System.out.println("American's average height"+height+"cm");
	}
	
	public void averageWeight() {
		weight = 75;
		System.out.println("American's average weight:" + weight + "kg");
	}
	
	
}
 
class Beijingman extends Chinese {
	public void beijingOpera() {
		System.out.println("花脸、青衣、花旦和老生");
	}
	
	public void averageHeight() {
		height = 172.5;
		System.out.println("北京人的平均身高:" + height + " 厘米");
	}
	
	public void averageWeight() {
		weight = 70;
		System.out.println("北京人的平均体重:" + weight + "千克");
	}
	
}

银行计算利息

假设银行Bank已经有了按整年year计算利息的一般方法,其中year只能取正整数。比如按整年计算的方法如下:

double computerInterest(){
interest=year*0.35*savedMoney;
return interest;
}

建设银行ConstructionBank是Bank的子类,准备隐藏继承的成员变量year,并重写计算利息的方法,即自己声明一个double型的year变量,比如,当year取值为5.216时,表示要计算5年零216天的利息,但希望首先按银行Bank的方法computerInterest()计算出5整年的利息,然后再自己计算216天的利息。那么,建设银行就必须把5.216的整数部分赋给隐藏的year,并让super调用隐藏的、按这年计算利息的方法。
要求ConstructionBank类和BankOfDalian类是Bank类的子类,ConstructionBank类和BankOfDalian类都使用super调用隐藏的成员变量和方法。


public class Main{
	public static void main(String args[]) {
		int amount = 8000;
		ConstructionBank bank1 = new ConstructionBank();
		bank1.savedMoney=amount;
		bank1.year=8.236;
		bank1.setInterestRate(0.035);
		double interest=bank1.computerInterest();
		BankOfDalian bank2=new BankOfDalian();
		bank2.savedMoney=amount;
		bank2.year=8.236;
		bank2.setInterestRate(0.035);
		double interest2=bank2.computerInterest();
		System.out.printf("两个银行利息相差%f元\n",interest2-interest);
	}
}

class Bank{
	int savedMoney;
	int year;
	double interest;
	double interestRate=0.29;
	public double computerInterest() {
		interest=year*interestRate*savedMoney;
		return interest;
	}
	public void setInterestRate( double rate) {
		interestRate=rate;
	}
}

class ConstructionBank extends Bank{
	double year;
	public double computerInterest() {
		super.year=(int)year;
		double r=year-(int)year;
		int day=(int)(r*1000);
		double yearInterest=super.computerInterest();
		double daylnterest=day*0.0001*savedMoney;
		interest=yearInterest+daylnterest;
		System.out.printf("%d元存在建设银行%d年零%d天的利息:%f元\n",savedMoney,super.year,day,interest);
		return interest;
	}
}

class BankOfDalian extends Bank{
	double year;
	public double computerInterest() {
		super.year=(int)year;
		double r=year-(int)year;
		int day=(int)(r*1000);
		double yearInterest=super.computerInterest();
		double dayInterest=day*0.00012*savedMoney;
		interest=yearInterest+dayInterest;
		System.out.printf("%d元存在大连银行%d年零%d天的利息:%f元\n",savedMoney,super.year,day,interest);
		return interest;
	}
}

公司支出的总薪水

要求一个abstract类,类名为Employee。Employee的子类有YearWorker、MonthWorker、WeekWorker。YearWorker对象按年龄领取薪水,MonthWorker按月领取薪水,WeekWorker按周领取薪水。Employee类有一个abstract方法:
public abstract earnings();
子类必须重写父类的earenings()方法,给出各自领取薪水的具体方式。
另外有一个Company类,该类用Employee对象数组作为成员,Employee对象数组的单元可以是YearWorker对象的上转型对象、MonthWorker对象的上转型对象或WeekWorker对象的上转型对象。程序能输出Company对象一年需要支付的薪水总额。


abstract class Employee {
    public abstract double earnings();   
}
class YearWorker extends Employee {     // YearWorker对象按年领取薪水
    public double earnings(){
        return 12000;
    } //重写earnings()方法,给出领取报酬的具体方式。
}
class MonthWorker extends Employee {    // MonthWorker对象按月领取薪水
    public double earnings(){
    return 12*2300;
    } //重写earnings()方法,给出领取报酬的具体方式。
}
class WeekWorker extends Employee {     // WeekWorker对象按周领取薪水
    public double earnings() {        //重写earnings()方法,给出领取报酬的具体方式。
    return 52*780;
  }
}

class Company {
    Employee[] employee;
    double salaries = 0;
    Company(Employee[] employee) {
      this.employee = employee;
   }
    public double salariesPay() {
       salaries = 0;
        for(int i=0;i<employee.length;i++) {
        salaries=salaries+employee[i].earnings();
        } //计算salaries。
        return salaries;
   }    
}

public class Main {
   public static void main(String args[]) {
      Employee [] employee = new Employee[29];   //公司有29名雇员
      for(int i=0;i<employee.length;i++) {   //雇员简单地分成三类
          if(i%3==0)
              employee[i] = new WeekWorker();
          else if(i%3==1)
              employee[i] = new MonthWorker();
           else if(i%3==2)
              employee[i] = new YearWorker();
      }
      Company company = new Company(employee);
      System.out.println("公司薪水总额:"+company.salariesPay()+"元");
   }
}

评价成绩

体操比赛计算选手成绩的办法是去掉一个最高分和最低分后再计算平均分,而学校考查一个班级的某科目的考试情况是计算全班同学的平均成绩。Gymnastics类和School类都实现了ComputerAverage接口,但实现的方式不同。

interface CompurerAverage {
	public double average(double x[]);
}

class Gymnastics implements CompurerAverage {
	public double average(double x[]) {
		int count=x.length;
		double aver=0,temp=0;
		for(int i=0;i<count;i++) {
			for(int j=i;j<count;j++) {
				if(x[j]<x[i]) {
					temp=x[j];
					x[j]=x[i];
					x[i]=temp;
					}
				}
			}
		for(int i=1;i<count-1;i++) {
			aver=aver+x[i];
			}
		if(count>2)
			aver=aver/(count-2);
		else
			aver=0;
		return aver;
	}
}
class School implements CompurerAverage {
	public double average(double[] x){
		int count=x.length;
		double aver=0;
		for(int i=0;i<count;i++){
			aver=aver+x[i];
			}
		aver=aver/count;
		return aver;
	}
}

public class Main{
	public static void main(String args[]) {
		double a[] = {9.89,9.88,9.99,9.12,9.69,9.76,8.97};
		double b[] ={89,56,78,90,100,77,56,45,36,79,98};
		CompurerAverage computer;
		computer=new Gymnastics();
		double result=computer .average(a);
		System.out.printf("%n");
		System.out.printf("体操选手最后得分:%5.3f\n",result);
		computer=new School();
		result=computer .average(b); 
		System.out.printf("班级考试平均分数:%-5.2f\n",result);
	}
}

货车的装载量

货车要装载一批货物,货物由电视机、计算机和洗衣机3种商品组成。卡车需要计算出整批货物的质量,具体需求如下:
(1)要求由一个ComputerWeight接口,该接口中有一个方法:
public double computerWeight()
(2)要求由3个实现该接口的类,即Television、Computer和WashMachine。这3个类通过实现接口computerTotalSales给出自重。
(3)要求有一个Truck类,该类以ComputerWeight接口类型的数组作为成员(Truck类面向接口),那么该数组的单元就可以存放Television对象的引用、Computer对象的引用或WashMachine对象的引用。程序能输出Truck对象所转载的货物的总质量。

interface ComputerWeight {
    public double computeWeight();
}
class Television implements ComputerWeight {
    public double computeWeight(){
        return 3.5;
    } //重写computeWeight()方法,返回自重值3.5。
}
class Computer implements ComputerWeight {
    public double computeWeight(){
        return 2.67;
    } //重写computeWeight()方法,返回自重值2.67。
}
class WashMachine implements ComputerWeight {
    public double computeWeight(){
        return 13.8;
    } //重写computeWeight()方法,返回自重值13.8。
}

class Truck {
    ComputerWeight [] goods;    //数组元素分别存放几个实现类的对象的引用
    double totalWeights=0;
    Truck(ComputerWeight[] goods) {
        this.goods=goods;
    }
    public void setGoods(ComputerWeight[] goods) {
        this.goods=goods;
    }
    public double getTotalWeights() {
        totalWeights=0;
        for(int i=0;i<goods.length;i++){
            totalWeights+=goods[i].computeWeight();
        } //计算totalWeights
        return totalWeights;
    }
}
public class Main {
    public static void main(String args[]) {
        ComputerWeight[] goods=new ComputerWeight[650]; //650件货物
        for(int i=0;i<goods.length;i++) {    //简单分成三类
            if(i%3==0)
                goods[i]=new Television();
            else if(i%3==1)
                goods[i]=new Computer();
            else if(i%3==2)
                goods[i]=new WashMachine();
        }
        Truck truck=new Truck(goods);
        System.out.printf("\n货车装载的货物重量:%-8.5f kg\n",truck.getTotalWeights());
        goods=new ComputerWeight[68];   //68件货物
        for(int i=0;i<goods.length;i++) {    //简单分成两类
            if(i%2==0)
                goods[i]=new Television();
            else
                goods[i]=new WashMachine();
        }
        truck.setGoods(goods);
        System.out.printf("货车装载的货物重量:%-8.5f kg\n",truck.getTotalWeights());
    }
}

小狗的状态

小狗在不同环境条件下可能呈现不同的状态表现,要求用接口封装小狗的状态,具体要求如下。
(1)编写一个接口DogState,该接口有一个名字为void showState()方法。
(2)编写Dog类,该类中有一个DogState接口声明的变量state。灵位,该类有一个show()方法,在该方法中让接口state回调showState()方法。
(3)编写若干个实现DogState接口的类,负责刻画小狗的各种状态。
(4)编写主类,在主类中测试小狗的各类状态。

interface DogState {
   public void showState();

}
class SoftlyState implements DogState{   
    public void showState() {
       System.out.println("听主人的命令");
    }
}
class MeetEnemyState implements DogState{
   public void showState()
    {
        System.out.println("狂叫,并冲上去很咬敌人");
    }

}
class MeetFriendState implements DogState{
   public void showState()
    {
        System.out.println("晃动尾巴,表示欢迎");
    }
}
class MeetAnotherDog implements DogState{
    public void showState()
    {
        System.out.println("嬉戏");
    }
}
class Dog{
   DogState  state;
   public void show() {
      state.showState();
   }
   public void setState(DogState s) {
      state = s;
   }
}
public class Main {
   public static void main(String args[]) {
      Dog yellowDog =new Dog();
      System.out.print("狗在主人面前:");
      yellowDog.setState(new SoftlyState());
      yellowDog.show();
      System.out.print("狗遇到敌人:");
      yellowDog.setState(new MeetEnemyState());
      yellowDog.show();
      System.out.print("狗遇到朋友:");
      yellowDog.setState(new MeetFriendState());
      yellowDog.show(); 
      System.out.print("狗遇到同伴:");
      yellowDog.setState(new MeetAnotherDog());
      yellowDog.show(); 
   }
}

实验五 内部类与异常类 (1)

检查危险品

车站检查危险品的设备,如果发现危险品会发出警告。编程模拟设备发现危险品。
编写一个Exception的子类DangerException,该子类可以创建异常对象,该异常对象调用toShow()方法输出“危险品!”。
编写一个Machine类,该类的checkBag(Goods goods)方法当发现参数goods是危险品时(goods的isDanger属性是true)将抛出DangerException异常。
程序在主类的main()方法中的try-catch语句的try部分让Machine类的实例调用checkBag (Good good)方法,如果发现危险品就在tr-catch语句的catch部分处理危险品。

class Goods {
	   boolean isDanger;
	   String name;
	   public void setIsDanger(boolean boo) {
	      isDanger = boo;}
	   public boolean isDanger() {
	      return isDanger;  
	      }
	   public void setName(String s) {
	      name = s;
	      }
	   public String getName() {
	      return name;
	      }
	   }
class DangerException extends Exception {
	   String message;
	   public DangerException() {
	       message = "危险品!";
	   }
	   public void toShow() {
	       System.out.print(message+" ");
	       }
	   }
class Machine {
	  public void checkBag(Goods goods) throws DangerException {
	     if(goods.isDanger()) {
	         DangerException danger=new DangerException();
	         throw new DangerException();
	     }
	     else {System.out.print(goods.getName()+"不是危险品! ");
	     }
	  }
	}
public class Main {
	public static void main(String args[]) {
		  Machine machine = new Machine();
		  String name[] ={"苹果","炸药","西服","硫酸","手表","硫磺"};
		  Goods [] goods = new Goods[name.length]; //检查6件货物  
		  for(int i= 0;i<name.length;i++) {
			 goods[i] = new Goods();
			 if(i%2==0) {
				goods[i].setIsDanger(false);
				goods[i].setName(name[i]);
			 }
			 else {
				goods[i].setIsDanger(true);
				goods[i].setName(name[i]);
			 }
		  }
		  for(int i= 0;i<goods.length;i++) {
			try {
				machine.checkBag(goods[i]);
				System.out.println(goods[i].getName()+"检查通过");
				}
			catch(DangerException e) {
			   e.toShow(); //e调用toShow()方法
			   System.out.println(goods[i].getName()+"被禁止!"); 
			}
		  }
	}
}

实验六 常用实用类 (6)

截取字符串

Sam想将得到的字符串按照给定区间,进行截取。请你帮他实现一下吧。(区间数字起始从1开始,不会出现越界的情况)

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        int begin = scanner.nextInt();
        int end = scanner.nextInt();
        System.out.println(str.substring(begin-1,end));
    }
}

子串出现频率

Sam得到一个主字符串以及一个子字符串,他想统计子字符串在主字符串中出现的次数。先输入主字符串,再输入子字符串。

import java.util.Scanner;  
  
public class Main {  
    public static void main(String[] args) {  
        Scanner scanner = new Scanner(System.in);   
        String mainString = scanner.nextLine();  
        String subString = scanner.nextLine();  
        int count = 0;  
        for (int i = 0; i <= mainString.length() - subString.length(); i++) {  
            if (mainString.regionMatches(i, subString, 0, subString.length())) {  
                count++;  
            }  
        }    
        System.out.println(count);  
    }  
}

统计指定字符的次数

Sam想统计一个字符串中指定字符的个数,请你帮他实现一下吧。


import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        // 创建Scanner对象用于获取用户输入
        Scanner scanner = new Scanner(System.in);
        String inputString = scanner.nextLine(); // 获取用户输入的字符串
        char targetChar = scanner.nextLine().charAt(0); // 获取用户输入的目标字符
        // 关闭Scanner对象
        scanner.close();
        // 统计字符出现的次数
        int count = 0;
        // 遍历字符串的每个字符
        for (int i = 0; i < inputString.length(); i++) {
            // 判断当前字符是否与目标字符相同
            if (inputString.charAt(i) == targetChar) {
                // 如果相同,计数器加1
                count++;
            }
        }
        // 打印最终计数器的值
        System.out.println(count);
    }
}

使用Scanner类

使用Scanner类的实例解析字符串“数学87分,物理76分,英语96分”中的考试成绩,并计算出总成绩以及平均分数。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String s = "数学87.0分, 物理76.0分,英语96.0分";
        String re = "[1234567890.]+" ;
        Pattern p = Pattern.compile(re) ;
        Matcher m = p.matcher(s) ;
        double sum = 0 ;
        while (m.find()) {
            String item = m.group() ;
            System.out.println(item) ;
            sum=sum+Double.parseDouble(item) ;
        }
        System.out.println("总分:"+sum+"分") ;
        System.out.println("平均分:"+sum/3+"分") ;
    }

}

替换错别字

在下列字符串中将“登录网站”错写为“登陆网站”,将“惊慌失措”错写为“惊慌失错”,“忘记密码,不要惊慌失错,请登录www.yy.cn或登录www.tt.cc”。编写一个Java应用程序,输出把错别字替换为正确用字的字符串。

import java.util.regex.*;
public class Main {
       public static void main(String args[]){
        String str ="忘记密码,不要惊慌失错,请登陆www.yy.cn或登陆www.tt.cc";
        Pattern pattern;
        Matcher matcher;
        String regex = "登陆";
        pattern = Pattern.compile(regex);
        matcher = pattern.matcher(str);
        while(matcher.find()){
            String s = matcher.group();
            System.out.print(matcher.start()+"位置出现:");
            System.out.println(s);
        }
        System.out.println("将\"登陆\"替换为\"登录\"的字符串:");
        String result = matcher.replaceAll("登录");
        System.out.println(result);
        pattern= Pattern.compile("惊慌失错");
        matcher = pattern.matcher(result);
        System.out.println("将\"惊慌失错\"替换为\"惊慌失措\"的字符串:");
        result = matcher.replaceAll("惊慌失措");
        System.out.println(result);
       }
}

处理大整数

编写一个Java应用程序,计算两个大整数的和、差、积和商,并计算出一个大整数的因子个数(因子中不包括1和大整数本身)。

import java.math.*;
public class Main{
    public static void main(String args[]) {
      BigInteger n1=new BigInteger("987654321987654321987654321"),
                 n2=new BigInteger("123456789123456789123456789"),
                 result=null;
       result=n1.add(n2);
       System.out.println("和:"+result.toString());
       result=n1.subtract(n2);
       System.out.println("差:"+result.toString());
       result=n1.multiply(n2);
       System.out.println("积:"+result.toString());
       result=n1.divide(n2);
       System.out.println("商:"+result.toString());
       BigInteger m=new BigInteger("17637"),
                  COUNT=new BigInteger("0"),
                  ONE=new BigInteger("1"),
                  TWO=new BigInteger("2");
      System.out.println(m.toString()+"的因子有:");
      for(BigInteger i=TWO;i.compareTo(m)<0;i=i.add(ONE)) {
          if((n1.remainder(i).compareTo(BigInteger.ZERO))==0) {
              COUNT=COUNT.add(ONE);
              System.out.print(" "+i.toString());
          }
      }
      System.out.println("");
      System.out.println(m.toString()+"一共有"+COUNT.toString()+"个因子");    
   }
}

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年12月27日
下一篇 2023年12月27日

相关推荐