Java 案例大全(详细)二

案例汇总

运动员和教练

多态,接口,抽象类


public class Test{
	public interface Speaking {
		public abstract void speak();
	}
	
	public abstract class Person {
		private String name;
		private int age;
		
		public Person() {}
		
		public Person(String name, int age) {
			this.name = name;
			this.age = age;
		}
		
		public void setName(String name) {
			this.name = name;
		}
		
		public void setAge(int age) {
			this.age = age;
		}
		
		public String getName() {
			return name;
		}
		
		public int getAge() {
			return age;
		}
		
		public abstract void eat();
		
		public void show() {
			System.out.println(this.getName() + ", " + this.getAge());
		}
	}
	
	public abstract class Coach extends Person {
		public Coach() {}
		
		public Coach(String name, int age) {
			super(name, age);
		}
		
		public void teach() {
			System.out.println("教学");
		}
	}
	
	public abstract class Player extends Person {
		public Player() {}
		
		public Player(String name, int age) {
			super(name, age);
		}
		
		public abstract void study();
	}
	
	public class BasketBallCoach extends Coach {
		public BasketBallCoach() {}
		
		public BasketBallCoach(String name, int age) {
			super(name, age);
		}
		
		public void teach() {
			System.out.println("教打篮球技巧");
		}
		
		public void eat() {
			System.out.println("吃大鱼大肉");
		}
	}
	
	public class TableTennisCoach extends Coach implements Speaking{
		public TableTennisCoach() {}
		
		public TableTennisCoach(String name, int age) {
			super(name, age);
		}
		
		public void teach() {
			System.out.println("教学乒乓球技巧");
		}
		
		public void eat() {
			System.out.println("吃山珍海味");
		}
		
		public void speak() {
			System.out.println("说流利的英语");
		}
	}
	
	public class BasketBallPlayer extends Player {
		public BasketBallPlayer() {}
		
		public BasketBallPlayer(String name, int age) {
			super(name, age);
		}
		
		public void eat() {
			System.out.println("吃大鱼大肉");
		}
		
		public void study() {
			System.out.println("学习篮球技术");
		}
	}
	
	public class TableTennisPlayer extends Player implements Speaking{
		public TableTennisPlayer() {}
		
		public TableTennisPlayer(String name, int age) {
			super(name, age);
		}
		
		public void eat() {
			System.out.println("吃山珍海味");
		}
		
		public void study() {
			System.out.println("学习乒乓球技巧");
		}
		
		public void speak() {
			System.out.println("说流利的英语");
		}
	}
	
	public static void main(String[] args) {
		Test t = new Test();
		System.out.println("----------------------------------");
		Coach bbc = t.new BasketBallCoach("姚明", 23);
		bbc.show();
		bbc.eat();
		bbc.teach();
		
		System.out.println("----------------------------------");
		TableTennisCoach ttc = t.new TableTennisCoach("刘国梁", 25);
		ttc.show();
		ttc.eat();
		ttc.teach();
		ttc.speak();
		
		System.out.println("----------------------------------");
		Player bbp = t.new BasketBallPlayer("天正", 19);
		bbp.show();
		bbp.eat();
		bbp.study();
		
		System.out.println("----------------------------------");
		TableTennisPlayer ttp = t.new TableTennisPlayer("马龙", 25);
		ttp.show();
		ttp.eat();
		ttp.study();
		ttp.speak();
		
	}
	
}

猫1

类名作为方法的形参
类名作为方法的返回值


public class Test{
	public class Cat {
		public void eat() {
			System.out.println("猫吃鱼");
		}
	}
	/*
	 * 	类作为形参,类作为返回值
	 * 	实际传递的是对象的地址值
	 */
	public class CatOperator {
		public void useCat(Cat c) {	//等价于 Cat c = new Cat();
			c.eat();
		}
		
		public Cat getCat() {
			Cat c = new Cat();
			return c;
		}
	}
	
	public static void main(String[] args) {
		Test t = new Test();
		CatOperator co = t.new CatOperator();
		Cat c = t.new Cat();
		co.useCat(c);
		co.getCat().eat();;
	}
}

猫2

抽象类名作为形参和返回值


public class Test{
	/*
	 * 	抽象类名作为形参和返回值
	 */
	public abstract class Animal {
		public abstract void eat();
	}
	
	public class Cat extends Animal {
		public void eat() {
			System.out.println("猫吃鱼");
		}
	}
	
	public class AnimalOperator {
		public void useAnimal(Animal a) {
			a.eat();
		}
		
		public Animal getAnimal() {
			//编译看左边,执行看右边
			Animal a = new Cat();
			return a;
		}
	}
	
	public static void main(String[] args) {
		AnimalOperator ao = new Test().new AnimalOperator();
		Animal a= new Test().new Cat();
		ao.useAnimal(a);
		ao.getAnimal().eat();
		
	}
}

猫3

接口作为形参和返回值


public class Test{
	/*
	 * 	接口名作为形参和返回值
	 */
	public interface Jumpping {
		void jump();
	}
	
	public class Cat implements Jumpping {
		public void jump() {
			System.out.println("猫可以跳高了");
		}
	}
	
	public class JumppingOperator {
		public void useJumpping(Jumpping j) {
			j.jump();
		}
		
		public Jumpping getJumpping() {
			Jumpping j = new Cat();
			return j;
		}
	}
	
	public static void main(String[] args) {
		JumppingOperator jo = new Test().new JumppingOperator();
		jo.useJumpping(jo.getJumpping());
		jo.getJumpping().jump();
	}
}

冒泡排序

冒泡排序


public class Test{
	/*
	 *	案例:冒泡排序
	 */
	public static String arrayToString(int[] array) {
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		for (int i = 0; i < array.length; i++) {
			if (i == array.length - 1) {
				sb.append(array[i]);
			} else {
				sb.append(array[i]).append(",");
			}
		}
		sb.append("]");
		return sb.toString();
	}
	
	public static void main(String[] args) {
		int array[] = {3, 1, 12, 44, 23, 10, 0};
		//冒泡排序
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array.length - i - 1; j++) {
				if (array[j] > array[j+1]) {
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
		System.out.println("排序后:" + arrayToString(array));
	}
}

案例:字符串中数据排列

类型转换

import java.util.Arrays;

public class Test{
	/*
	 * 案例:字符串中数据排列
	 */
	public static void main(String[] args) {
		String s = "91 27 46 38 50";
		String[] array = s.split(" ");
		int[] arr = new int[array.length];
		for (int i = 0; i < array.length; i++) {
			arr[i] = Integer.parseInt(array[i]);
		}
		Arrays.sort(arr);
		
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		for (int i = 0; i < arr.length; i++) {
			if (i == arr.length - 1) {
				sb.append(arr[i]);
			} else {
				sb.append(arr[i]).append(" ");
			}
		}
		sb.append("]");
		System.out.println(sb.toString());
	}
}

日期工具类

Date类,SimpleDateFormat类

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
	 * 案例:日期工具类
	 * 工具类:构造方法私有,成员方法静态
	 */
	public class DateUtils {
		private DateUtils() {}
		
		public static String dateToString(Date date, String format) {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			String s = sdf.format(date);
			return s;
		}
		
		public static Date stringToDate(String s, String format) throws ParseException {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			Date date = sdf.parse(s);
			return date;
		}
	}
import java.util.Date;
import java.text.ParseException;

public class Test{
	
	public static void main(String[] args) throws ParseException {
		Date date = new Date();
		String s1 = DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss");
		System.out.println(s1);
		
		String ss = "2021-09-11 09:30:22"; 
		Date dd = DateUtils.stringToDate(ss, "yyyy-MM-dd HH:mm:ss");
		System.out.println(dd);
	}
}

Calendar类

日历类

import java.util.Calendar;

public class Test{
	/*
	 * 日历类
	 */
	public static void main(String[] args) {
		//需求1:3年前的今天
		Calendar c = Calendar.getInstance();
		c.add(Calendar.YEAR, -3);
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DATE);
		System.out.println("日期为:" + year + "-" + month + "-" + day);
		
		//需求2:10年后的5天前
		c.add(Calendar.YEAR, 10);
		c.add(Calendar.DATE, -5);
		int y = c.get(Calendar.YEAR);
		int m = c.get(Calendar.MONTH) + 1;
		int d = c.get(Calendar.DATE);
		System.out.println("日期为:" + y + "-" + m + "-" + d);
		
		//设置当前日历的年月日
		c.set(2001, 11, 1);
		int year1 = c.get(Calendar.YEAR);
		int month1 = c.get(Calendar.MONTH) + 1;	//Month 值是基于 0 的。例如,0 表示 January。
		int day1 = c.get(Calendar.DATE);
		System.out.println("日期为:" + year1 + "-" + month1 + "-" + day1);
	}

}

二月天

Calendar类

import java.util.Calendar;
import java.util.Scanner;

public class Test{
	/*
	 * 案例:二月天
	 */
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int year = sc.nextInt();
		
		Calendar c = Calendar.getInstance();
		c.set(year, 2, 1);	//Month 值是基于 0 的。例如,0 表示 January。
		c.add(Calendar.DATE, -1);
		int day = c.get(Calendar.DATE);
		System.out.println(year + "年" + "二月有" + day + "天");
		sc.close();
	}

}

自定义异常

异常类使用

import java.util.Scanner;

public class Test{
	/*
	 * 案例:自定义异常类
	 */
	public class ScoreException extends Exception{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public ScoreException() {}
		
		public ScoreException(String message) {
			super(message);
		}
	}
	
	public class Teacher{
		public Teacher() {}
		
		public void checkScore(int score) throws ScoreException {
			if (score < 0 || score > 100) {
				throw new ScoreException("分数有误!!!");
//				System.out.println("分数有误!!!");
			} else {
				return;
			}
		}
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入分数:");
		int score = sc.nextInt();
		sc.close();
		
		Teacher t = new Test().new Teacher();
		try{
			t.checkScore(score);
		} catch(ScoreException e) {
			e.printStackTrace();
		}
	}
}

遍历ArrayList

集合

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Test{
	/*
	 *	 案例:遍历ArrayList
	 */
	public static void main(String[] args) {
		//方法一:For-Each遍历
		List<String> list = new ArrayList<>();
		list.add("hello");
		list.add("java");
		list.add("world");
		for (String s : list) {
			System.out.println(s);
		}
		
		System.out.println("---------------");
		
		//方法二:把链表变为数组进行遍历
		String[] array = new String[list.size()];
		list.toArray(array);
		for (int i = 0; i < array.length; i++) {
			System.out.println(array[i]);
		}
		
		System.out.println("---------------");
		
		//方法三:使用迭代器进行遍历,该方法可以不用担心在遍历的过程中会超出集合的长度。
		Iterator<String> i = list.iterator();
		while(i.hasNext()) {
			System.out.println(i.next());
		}
			
		System.out.println("---------------");
		
		//方法四:
		for (int x = 0; x < list.size(); x++){
			System.out.println(list.get(x));
		}
	}
}

遍历Map

集合类

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Test{
	/*
	 *	 案例:遍历Map
	 */
	public static void main(String[] args) {
		//方法一:通过Map.keySet遍历key和value
		Map<Integer, String> map = new HashMap<Integer, String>(); 
		map.put(1, "张三");
		map.put(2, "李四");
		map.put(3, "王五");
		for (Integer i : map.keySet()) {
			System.out.println(i + "," + map.get(i));
		}
		
		System.out.println("---------------");
		
		//方法二:通过Map.entrySet使用iterator遍历key和value:
		Iterator<Map.Entry<Integer, String>> i = map.entrySet().iterator();
		while (i.hasNext()) {
			Map.Entry<Integer, String> entry = i.next();
			System.out.println(entry.getKey() + "," + entry.getValue());
		}
		
		
		System.out.println("---------------");
		
		//方法三:推荐,尤其是容量大时,通过Map.entrySet遍历key和value
		for (Map.Entry<Integer, String> entry : map.entrySet()) {
			System.out.println(entry.getKey() + "," + entry.getValue());
		}

		System.out.println("---------------");
		
		//方法四:通过Map.values()遍历所有的value,但不能遍历key
		for (String v : map.values()) {
			System.out.println(v);
		}
	}
}

判断是否为数字

练习

import java.util.regex.Pattern;

public class Test{
	/*
	 *	 案例:判断是否为数字
	 */
	
	//方法一:用Java自带方法(非负数并且是整数)
	public static  boolean isNumeric(String string) {
		for (int i = 0; i < string.length(); i++) {
			if (!Character.isDigit(string.charAt(i))) {
				return false;
			}
		}
		return true;
	}
	
	//方法二:推荐,速度最快  (只能是整数)
	public static boolean isInteger(String string) {
		Pattern pattern = Pattern.compile("^[-\\ ]?[\\d]*$");
		return pattern.matcher(string).matches();
	}
	
	//方法三:用ascii码  (只能是正整数)
	public static boolean isNumeric1(String str){
	    for(int i=str.length();--i>=0;){
	        int chr=str.charAt(i);
	        if(chr<48 || chr>57)
	            return false;
	    }
	    return true;
	}
	
	public static void main(String[] args) {
		String string = "-10000";
		boolean flag1 = isNumeric(string);
		boolean flag2 = isInteger(string);
		boolean flag3 = isNumeric1(string);
		System.out.println("数字" + flag1);
		System.out.println("数字" + flag2);
		System.out.println("数字" + flag3);
	}
}

自然排序Comparable

TreeSet


public class Student implements Comparable<Student>{
	private String name;
	private int id;
	private int age;
	
	public Student() {}
	
	public Student(String name, int age) {
		this.name = name; 
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getAge() {
		return age;
	}

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

	@Override
	public int compareTo(Student s) {
	    //按照年龄从小到大排序
		int num = this.age - s.age;
	    //年龄相同时,按照姓名的字母顺序排序
		int num2 = num == 0 ? this.name.compareTo(s.name) : num;//(重复元素)
		return num2;
	}
	
}

import java.util.TreeSet;

public class Test{
	public static void main(String[] args) {
		TreeSet<Student> ts = new TreeSet<Student>();
		Student s1=new Student("xishi",29);
		Student s2=new Student("wangzhaojun",28);
		Student s3=new Student("diaochan",30);
		Student s4=new Student("yangyuhuan",33);

		Student s5=new Student("linqingxia",33);
		Student s6=new Student("linqingxia",33);


		ts.add(s1);
		ts.add(s2);
		ts.add(s3);
		ts.add(s4);
		ts.add(s5);
		ts.add(s6);

		for (Student s : ts) {
			System.out.println(s.getName() + "," + s.getAge());
		}
	}
}

成绩排序

TreeSet

import java.util.Comparator;
import java.util.TreeSet;

public class Test{
	/*
	 * 案例:成绩排序
	 * 
	 */
	public static void main(String[] args) {
		TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
			public int compare(Student s1, Student s2) {
				//int num=(s2.getChinese()+s2.getMath())-(s1.getChinese()+s1.getMath());
		        //主要条件
		        int num = s2.getSum() - s1.getSum();
		        //次要条件
		        int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
		        int num3 = num == 0 ? s1.getName().compareTo(s2.getName()) : num2;
		        return num3;
			}
		});
	
		Student s1=new Student("xishi",98,100);
		Student s2=new Student("wangzhaojun",95,95);
		Student s3=new Student("diaochan",100,93);
		Student s4=new Student("yangyuhuan",100,97);

//		Student s5=new Student("linqingxia",98,98);
		Student s5=new Student("linqingxia",98,98);
		Student s6=new Student("zhaoyun",97,99);
		
		ts.add(s1);
		ts.add(s2);
		ts.add(s3);
		ts.add(s4);
		ts.add(s5);
		ts.add(s6);
		
		for (Student s : ts) {
			System.out.println(s.getName() + "," + s.getChinese() + "," + s.getMath() + "," +s.getSum());
		}
	}
}

public class Student{
	private String name;
	private int age;
	private int chinese;
	private int math;
	
	public Student() {}
	
	public Student(String name, int age) {
		this.name = name; 
		this.age = age;
	}
	
	public Student(String name, int chinese, int math) {
		this.chinese = chinese;
		this.math = math;
		this.name = name;
	}
	
	public int getChinese() {
		return chinese;
	}

	public void setChinese(int chinese) {
		this.chinese = chinese;
	}

	public int getMath() {
		return math;
	}

	public void setMath(int math) {
		this.math = math;
	}

	public int getSum() {
		return this.chinese + this.math;
	}

	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;
	}

}

不重复的随机数

TreeSet

import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

public class Test{
	/*
	 * 案例:不重复的随机数
	 * 
	 */
	public static void main(String[] args) {
		Set<Integer> set = new TreeSet<Integer>();
		Random r = new Random();
		int x = 0;
		while (set.size() < 10) {
			x = r.nextInt(20) + 1;
			set.add(x);
		}
		for (Integer i : set) {
			System.out.println(i);
		}
	}
}

字符流

FileOutputStream、OutputStream、OutputStreamReader、OutputStreamWriter

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Test{
	public static void main(String[] args) throws IOException {
        File f = new File("a.txt");
        FileOutputStream fos = new FileOutputStream(f);
        // 构建FileOutputStream对象,文件不存在会自动新建

        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        // 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk

        osw.append("中文输入");
        // 写入到缓冲区

        osw.append("\r\n");
        // 换行

        osw.append("English");
        // 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入

        osw.close();
        // 关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉

        fos.close();
        // 关闭输出流,释放系统资源

        FileInputStream fis = new FileInputStream(f);
        // 构建FileInputStream对象

        InputStreamReader osr = new InputStreamReader(fis, "UTF-8");
        // 构建InputStreamReader对象,编码与写入相同

        StringBuffer sb = new StringBuffer();
        while (osr.ready()) {
            sb.append((char) osr.read());
            // 转成char加到StringBuffer对象中
        }
        System.out.println(sb.toString());
        osr.close();
        // 关闭读取流

        fis.close();
        // 关闭输入流,释放系统资源
	}
}

创建目录

mkdir()、mkdirs()

import java.io.File;

public class Test{
	/*
	 * 创建目录  mkdir()、mkdirs()
	 */
	public static void main(String[] args){
        String dirname = "/tmp/user/java/bin";
        File d = new File(dirname);
        // 现在创建目录
        d.mkdirs();
	}
}

读取目录

isDirectory()、list()

import java.io.File;

public class Test{
	/*
	 * 案例:读取目录  isDirectory()、list()
	 */
	public static void main(String[] args){
        String dirname = "/class 3";
        File f1 = new File(dirname);
        if (f1.isDirectory()) {
            System.out.println("目录 " + dirname);
            String s[] = f1.list();
            for (int i = 0; i < s.length; i++) {
                File f = new File(dirname + "/" + s[i]);
                if (f.isDirectory()) {
                    System.out.println(s[i] + " 是一个目录");
                } else {
                    System.out.println(s[i] + " 是一个文件");
                }
            }
        } else {
            System.out.println(dirname + " 不是一个目录");
        }
	}
}

删除目录

delete()、listFiles()

import java.io.File;

public class Test{
	/*
	 * 案例:删除目录  delete()、listFiles()必须保证该目录下没有其他文件才能正确删除,否则将删除失败。
	 */
	public static void main(String[] args){
        // 这里修改为自己的测试目录
        File folder = new File("/tmp/java/");
        deleteFolder(folder);
    }

    // 删除文件及目录
    public static void deleteFolder(File folder) {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    deleteFolder(f);
                } else {
                    f.delete();
                }
            }
        }
        folder.delete();
    }
}
  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值