java复习第十五天异常,file类,递归,集合面试题

这篇博客主要探讨了Java中的集合面试题,包括使用Comparator和Comparable排序、HashSet去重、ListIterator操作、集合嵌套及遍历、List排序、Map与List嵌套等实际问题。同时,详细介绍了异常处理的语法,如Throwable、try-catch、throws、throw的使用,以及异常处理的注意事项。此外,还讲解了递归的概念和File类的应用,包括文件判断和获取功能,并给出了面试中可能遇到的File类相关问题。
摘要由CSDN通过智能技术生成

集合面试题:


一、使用Comparator和Comparable对象数组进行排序和查找;数组必须是引用类型

import java.util.Comparator;


public class Test {
	public static void main(String[] args) {
		Person p = new Person("zhangsan", 18, '男');
		Person p2 = new Person("zhangsan", 20, '男');
		Person p3 = new Person("lisi", 18, '男');
		Person p4 = new Person("wangwu", 18, '男');
		Person p5 = new Person("zhaoliu", 8, '女');
		Person p6 = new Person("dahua", 9, '男');
		Person[] arr = { p, p2, p3, p4, p5, p6 };

		Arrays.sort(arr, new Comparator<Person>() {
			@Override
			public int compare(Person o1, Person o2) {
				// o1的成员和o2的成员比较:升序
				// o2的曾有和o1的成员比较:降序
				// 以年龄为主进行降序,如果年龄一致就以姓名为主进行降序
				if (o2.getAge() == o1.getAge()) {
					return o2.getName().compareTo(o1.getName());
				} else {
					return o2.getAge() - o1.getAge();
				}
			}
		});

		for (Person value : arr) {
			System.out.println(value);
		}
	}
}
public class Person implements Comparable<Person> {
	private String name;
	private int age;
	private char sex;

	public Person() {
		super();
	}

	public Person(String name, int age, char sex) {
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	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 char getSex() {
		return sex;
	}

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

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}

	@Override
	public int compareTo(Person o) {
		// this的成员和o的成员比较:升序
		// 先以名字为主进行升序,如果名字相同再以年龄为主进行升序
		if (this.getName().equals(o.getName())) {
			return this.getAge() - o.getAge();
		} else {
			return this.getName().compareTo(o.getName());
		}
		// o的成员和this的成员比较:降序
	}
}


二、在HashSet集合中添加三个Student对象,把姓名相同的人当做同一个人,禁止重复添加

Student对象有name,age,sex,address等属性

public class Test2 {
	public static void main(String[] args) {
		HashSet<Student> hashSet = new HashSet<Student>();
		hashSet.add(new Student("张三", 18, '男', "北京"));
		hashSet.add(new Student("张三", 20, '女', "北京"));
		hashSet.add(new Student("李四", 18, '男', "北京"));
		hashSet.add(new Student("李四", 8, '男', "北京"));
		for (Student s : hashSet) {
			System.out.println(s);
		}
	}
}
package cn.edu360;

public class Student implements Comparable<Student>{
	private String number;
	private String name;
	private int age;
	private char sex;
	private String address;
	public Student() {
	}
	public Student(String name, int age, char sex, String address) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.address = address;
	}
}
三、 定义一个List对象,如下
List <String>list = new ArrayList<String>();
在list中添加元素,nihao,wohao,dajiahao,nihao
在list的第二个位置添加元素,tahao
用Iterator迭代器遍历打印list中元素

在打印时,将list中的nihao,修改为nibuhao(提示:需要用到ListIterator)

public class Test3 {
	public static void main(String[] args) {
		List <String>list = new ArrayList<String>();
		list.add("nihao");
		list.add("wohao");
		list.add("dajiahao");
		list.add("nihao");
		System.out.println(list);//[nihao, wohao, dajiahao, nihao]
		list.add(1, "tahao");
		System.out.println(list);//[nihao, tahao, wohao, dajiahao, nihao]
		ListIterator<String> iterator = list.listIterator();
		while(iterator.hasNext()){
			String s = iterator.next();
			if(s.equals("nihao")){
				iterator.set("nibuhao");
			}
			System.out.println(s);
		}
		System.out.println("---------------------------------------");
		for (String s : list) {
			System.out.println(s);
		}
	}
}
四、 Map接口和HashMap练习
定义一个Map对象,如下
Map<String,String> map = newHashMap<String,String>();
在map中添加键值对(“1”,“xiaohong”)、(“2”,”xiaowang”)、(“3”,”xiaoli”)
将map中的键值对打印出来

import java.util.HashMap;
import java.util.Map;
public class Test4 {
	public static void main(String[] args) {
		Map<String,String> map = new HashMap<String,String>();
		map.put("1", "xiaohong");
		map.put("2", "xiaowang");
		map.put("3", "xiaoli");
		
		System.out.println(map);
	}
}

五、定义一个ArrayList<Student> ,放入5个Student对象,

然后计算出list中所有Student对象的平均分及平均年龄,并将结果打印到控制台

public class Test5 {
	public static void main(String[] args) {
		ArrayList<Student> list = new ArrayList<Student>();
		list.add(new Student("张三", 18, '男', "南京", 80));
		list.add(new Student("李四", 19, '女', "杭州", 88));
		list.add(new Student("王五", 17, '男', "北京", 70));
		list.add(new Student("赵六", 19, '女', "广州", 66));
		list.add(new Student("小花", 18, '女', "上海", 90));
		list.add(new Student("大花", 20, '男', "深圳", 75));

		// 保存年龄
		int sumAge = 0;
		// 保存分数
		float sumScore = 0;
		for (Student s : list) {
			sumAge += s.getAge();
			sumScore += s.getScore();
		}

		float avgAge = 1.0f * sumAge / list.size();
		float avgScore = sumScore / list.size();

		System.out.println("avgAge=" + avgAge + ",avgScore=" + avgScore);//avgAge=18.5,avgScore=78.166664
	}
}

六、 使用集合嵌套将以下数据进行存储并遍历
北京省
北京市
西城区
崇文区
宣武区
丰台区
石景山区
安徽省
合肥市
瑶海区
包河区
六安市
金安区
裕安区
叶集区
江苏省
南京市
雨花台区
玄武区
无锡市
锡山区

滨湖区 

public class Test6 {
	public static void main(String[] args) {
		LinkedHashMap<String, LinkedHashMap<String, ArrayList<String>>> provinces = new LinkedHashMap<String, LinkedHashMap<String, ArrayList<String>>>();

		// 北京省
		LinkedHashMap<String, ArrayList<String>> citys = new LinkedHashMap<String, ArrayList<String>>();
		ArrayList<String> areas = new ArrayList<String>();
		areas.add("西城区");
		areas.add("崇文区");
		areas.add("宣武区");
		areas.add("丰台区");
		areas.add("石景山区");
		citys.put("北京市", areas);
		provinces.put("北京省", citys);

		// 安徽省
		citys = new LinkedHashMap<String, ArrayList<String>>();
		areas = new ArrayList<String>();
		areas.add("瑶海区");
		areas.add("包河区");
		citys.put("合肥市", areas);
		areas = new ArrayList<String>();
		areas.add("金安区");
		areas.add("裕安区");
		areas.add("叶集区");
		citys.put("六安市", areas);
		provinces.put("安徽省", citys);

		// 江苏省
		citys = new LinkedHashMap<String, ArrayList<String>>();
		areas = new ArrayList<String>();
		areas.add("雨花台区");
		areas.add("玄武区");
		citys.put("南京市", areas);
		areas = new ArrayList<String>();
		areas.add("锡山区");
		areas.add("滨湖区 ");
		citys.put("无锡市", areas);
		provinces.put("江苏省", citys);

		for (Entry<String, LinkedHashMap<String, ArrayList<String>>> entry : provinces.entrySet()) {
			String provinceName = entry.getKey();
			System.out.println(provinceName);
			citys = entry.getValue();
			for (Entry<String, ArrayList<String>> entry2 : citys.entrySet()) {
				String cityName = entry2.getKey();
				System.out.println("\t" + cityName);
				areas = entry2.getValue();
				for (String areaName : areas) {
					System.out.println("\t\t" + areaName);
				}
			}
		}
	}
}

七、编写程序,随机生成5个1-10之间的随机数,存入一个List集合中,编写方法对List集合进行排序

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;

//编写程序,随机生成5个1-10之间的随机数,存入一个List集合中,编写方法对List集合进行排序
public class Test7 {
	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		Random r = new Random();
		for (int i = 0; i < 5; i++) {
			list.add(r.nextInt(10) + 1);
		}
		Collections.sort(list,new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				return o2-o1;
			}
		});
		System.out.println(list);
	}
}
八、  有7个学生信息,内容如下:
学号,姓名,年龄,总分
173620,王康,22,470
173623,刘明,22,450
173628,王瑞,20,460
173624,李玉,21,432
173622,李倩,24,480
173634,刘军,23,550
173632,刘向,20,650

需求一:写程序统计各姓氏的学生人数,并将结果打印到控制台
比如:
王,2
李,2
.....
需求二:
将数据读取到ArrayList<Student>中,然后按照学号为第一条件、年龄为第二条件、总分为第三条件的方式进行排序,

并将排序之后的结果输出到控制台

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
public class Test8 {
	public static void main(String[] args) {
		ArrayList<Student> list = new ArrayList<Student>();
		list.add(new Student("173620", "王康", 22, 470));
		list.add(new Student("173623", "刘明", 22, 450));
		list.add(new Student("173628", "王瑞", 20, 460));
		list.add(new Student("173624", "李玉", 21, 432));
		list.add(new Student("173622", "李倩", 24, 480));
		list.add(new Student("173634", "刘军", 23, 550));
		list.add(new Student("173632", "刘向", 20, 650));

		LinkedHashMap<String, Integer> hashMap = new LinkedHashMap<String, Integer>();

		for (Student s : list) {
			String name = s.getName().substring(0, 1);
			if (hashMap.containsKey(name)) {// 说明map中有这个姓
				hashMap.put(name, hashMap.get(name) + 1);
			} else {// map中没有这个姓,没有就直接添加
				hashMap.put(name, 1);
			}
		}
		for (Entry<String, Integer> entry : hashMap.entrySet()) {
			String key = entry.getKey();
			Integer value = entry.getValue();
			System.out.println(key + "," + value);
		}
		System.out.println("----------------------------------------");
		Collections.sort(list);
		for (Student s: list) {
			System.out.println(s);
			
		}
	}
}

九、Map集合嵌套List集合。
要求输出结果:
三国演义
吕布
周瑜
笑傲江湖
令狐冲
林平之
神雕侠侣
郭靖

杨过  


import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
public class Test9 {
	public static void main(String[] args) {
		LinkedHashMap<String,ArrayList<String>> map = new LinkedHashMap<String,ArrayList<String>>();
		ArrayList<String> list = new ArrayList<String>();
		list.add("吕布");
		list.add("周瑜");
		map.put("三国演义", list);
		
		list = new ArrayList<String>();
		list.add("令狐冲");
		list.add("林平之");
		map.put("笑傲江湖", list);
		
		list = new ArrayList<String>();
		list.add("郭靖");
		list.add("杨过  ");
		map.put("神雕侠侣", list);
		
		for(Entry<String,ArrayList<String>> entry : map.entrySet()){
			String name = entry.getKey();
			System.out.println(name);
			ArrayList<String> list2 = entry.getValue();
			for (String n : list2) {
				System.out.println("\t"+n);
			}
		}
	}
}

十、List集合嵌套Map集合。
 要求输出结果:
周瑜---小乔
吕布---貂蝉

郭靖---黄蓉
杨过---小龙女

令狐冲---任盈盈

林平之---岳林姗

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
public class Test10 {
	public static void main(String[] args) {
		ArrayList<LinkedHashMap<String, String>> list = new ArrayList<LinkedHashMap<String, String>>();
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("周瑜", "小乔");
		map.put("吕布", "貂蝉");
		list.add(map);

		map = new LinkedHashMap<String, String>();
		map.put("郭靖", "黄蓉");
		map.put("杨过", "小龙女");
		list.add(map);

		map = new LinkedHashMap<String, String>();
		map.put("令狐冲", "任盈盈");
		map.put("林平之", "林平之");
		list.add(map);

		for (LinkedHashMap<String, String> map2 : list) {
			for (Entry<String, String> entry : map2.entrySet()) {
				System.out.println(entry.getKey() + "---" + entry.getValue());
			}
			System.out.println();
		}
	}
}

十一、异常的用法与语法

(1)

一个问题我们用Throwable来表示,这个问题根据严重性又分为(Error)错误和异常(Exception)

   Throwable:
Error:假设win7需要10个G的安装空间,但是硬盘空间不足,这时候报错了,这个错误就是严重的错误,跟程序无关
   Exception:
  运行时期异常:就是RuntimeException及其子类的异常,是那些可能在 Java 虚拟机正常运行期间抛出的异常的超类
  可以更改代码,也可以使用处理方式(try...catch;throws,throw)
   编译时期异常:非RuntimeException及其子类的异常,在编译时期就会报错的异常

   只能使用处理方式(try...catch;throws,throw)

public class ExceptionDemo {
	public static void main(String[] args) {
		//运行时期异常
		String s = null;
		System.out.println(s.length());//java.lang.NullPointerException
		int i = 1/0;//java.lang.ArithmeticException
		sop();//java.lang.StackOverflowError
		
		//编译时期异常
		//new SimpleDateFormat().parse("");
	}
	
	public static void sop(){
		sop();
	}
}

(2)如果异常出现了,我们不处理,那么就是JVM处理
 * JVM默认的处理方案:
 * 程序停止
 * 将出现异常的信息打印在控制台
 * 将异常出现的位置打印在控制台

 * 真正开发的时候,一部分的情况是需要我们自己来处理这个异常的

public class ExceptionDemo {
	public static void main(String[] args) {
		//运行时期异常
		String s = null;
		System.out.println(s.length());//java.lang.NullPointerException
		int i = 1/0;//java.lang.ArithmeticException
		sop();//java.lang.StackOverflowError
		
		//编译时期异常
		//new SimpleDateFormat().parse("");
	}
	public static void sop(){
		sop();
	}
}
(3)异常的格式:
 * 处理异常方式:try...catch
 * 	try{
 * 		可能出现异常的代码
 * 	}catch(异常的类名 变量){
 * 		处理方案
 * 	}

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class ExceptionDemo3 {
	public static void main(String[] args) {
		test6();
		System.out.println("over");
	}
	//大多数真正开发中处理异常的方式:捕获一个最大的异常
	private static void test6() {
		try {
			new ServerSocket(80);
			new ServerSocket(80);
			new SimpleDateFormat().parse("");
			new FileInputStream(new File(""));
		} catch (Exception  e) {
			e.printStackTrace();//打印异常信息,及时解决问题,然后上线之后这个问题就不会存在了
		}
	}

	//JDK1.7新特性,多个异常捕获时可以使用"|"整合到一起,但是不能存在子父类关系
	private static void test5() {
		try {
			new ServerSocket(80);
			new ServerSocket(80);
			new SimpleDateFormat().parse("");
			new FileInputStream(new File(""));
		} catch (IOException|ParseException e) {
			System.out.println("你需要解析的文本格式和模板格式不匹配");
		}
	}

	//多个异常合并捕获时,如果捕获的异常中存在子父类关系,那么父类异常一定要放在最后面
	private static void test4() {
		try {
			new ServerSocket(80);
			new ServerSocket(80);
			new SimpleDateFormat().parse("");
			new FileInputStream(new File(""));
		} catch (ParseException e) {
			System.out.println("你需要解析的文本格式和模板格式不匹配");
		} catch (FileNotFoundException e) {
			System.out.println("文件没有找到");
		}catch(Exception e){//不论什么异常,我都可以捕获
			System.out.println("你出问题了");
		}
	}

	// 多个异常合并到一起
	private static void test3() {
		try {
			new SimpleDateFormat().parse("");
			new FileInputStream(new File(""));
		} catch (ParseException e) {
			System.out.println("你需要解析的文本格式和模板格式不匹配");
		} catch (FileNotFoundException e) {
			System.out.println("文件没有找到");
		}
	}

	// 两个异常
	private static void test2() {
		try {
			new SimpleDateFormat().parse("");
		} catch (ParseException e) {
			System.out.println("你需要解析的文本格式和模板格式不匹配");
		}
		try {
			new FileInputStream(new File(""));
		} catch (FileNotFoundException e) {
			System.out.println("文件没有找到");
		}
	}

	// 一个异常
	private static void test() {
		try {
			new SimpleDateFormat().parse("18-4-18 上午11:13");
		} catch (ParseException e) {
			System.out.println("你需要解析的文本格式和模板格式不匹配");
		}
	}
}

(4)常用的异常方法

public class ExceptionDemo4 {
	public static void main(String[] args) {

		try {
			int i = 1 / 0;// 运行时期异常
		} catch (Exception e) {
			// public String getMessage()返回此 throwable 的详细消息字符串
			//System.out.println(e.getMessage());// by zero
			
			// public String toString()返回此 throwable 的简短描述
			//System.out.println(e.toString());//java.lang.ArithmeticException: / by zero
			
			// public void printStackTrace()将此 throwable 及其追踪输出至标准错误流
			e.printStackTrace();
			/*
			 * 	java.lang.ArithmeticException: / by zero
				at cn.edu360.ExceptionDemo4.main(ExceptionDemo4.java:8)
			 */
			
			// public void printStackTrace(PrintWriter s)将此 throwable 及其追踪输出到指定的PrintWriter
			try {
				//把异常保存到文件中
				PrintStream s = new PrintStream("D:/error.log");
				e.printStackTrace(s);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}

		System.out.println("over");
	}
}

(5)加入final释放资源的语法

import java.util.Scanner;

/*
 * 释放资源操作:try...catch...finally
 * 	try{
 * 		可能出现问题的代码
 * 	}catch(异常的类名 变量名){
 * 		处理方案
 * 	}finally{
 * 		一定会执行的代码
 * 	}
 */
public class ExceptionDemo5 {
	public static void main(String[] args) {
		Scanner sc = null;
		try {
			int a = 1 / 0;// 假设这里出现了异常,那么sc就没有被赋值
			sc = new Scanner(System.in);
			int i = sc.nextInt();// 如果这里出现了问题,sc的close方法就执行不到了
			System.out.println(i);
			// sc.close();//关闭资源
		} catch (Exception e) {
			e.printStackTrace();
			//return;
			System.exit(0);//只有在JVM挂掉的时候,finally里面的代码才不会执行
		} finally {
			System.out.println("哈哈哈");
			// 判断sc不能为null才去关流
			if (null != sc) {
				sc.close();
			}
		}
	}
}

(6)关键字throws

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/*
 * throws:是将异常抛给其他人来处理,它是直接在方法的后面抛出一个或多个异常,如果抛出多个异常的话,那么需要用","隔开
 */
public class ExceptionDemo6 {
	public static void main(String[] args) throws Exception  {
		test("18-4-18 上午11:13");
		test2();
		test3();
		
		System.out.println("over");
	}
	
	//谁来调用这个方法,谁来处理这个异常
	public static void test(String source)throws ParseException{
		new SimpleDateFormat().parse(source);
	}
	
	//谁来调用这个方法,谁来处理这个异常
	public static void test2() throws FileNotFoundException{
		new FileInputStream(new File(""));
	}
	
	public static void test3()throws NullPointerException{
		
	}
}

(7)关键字throw

import java.text.ParseException;
import java.text.SimpleDateFormat;

/*
 * throw:抛出某个异常具体的对象,在方法体内部使用,一次只能抛出一个异常
 */
public class ExceptionDemo7 {
	public static void main(String[] args) throws ParseException {
		test2();
	}

	public static void test2()throws ParseException{
		try {
			new SimpleDateFormat().parse("");
		} catch (ParseException e) {
			throw new ParseException("要解析的文本和模板格式不匹配",18);
		}
	}
	
	//运行时期异常
	public static void test() {
		try {
			int i = 1 / 0;
		} catch (Exception e) {
			// public ArithmeticException(String s)构造具有指定详细消息的
			// ArithmeticException
			throw new ArithmeticException("除数不能为零");
		}
	}
}

(8)具体案例中的异常

public class ExceptionDemo8 {
	public static void main(String[] args) throws AgeException {
		Person p = new Person("张三", -18, '男');
		System.out.println(p);//Person [name=张三, age=18, sex=男]

	}
}
public class Person {
	private String name;
	private int age;
	private char sex;
	public Person() {
		super();
	}
	public Person(String name, int age, char sex)throws AgeException {
		super();
		this.name = name;
		this.sex = sex;
		checkAge(age);
		this.age = age;
	}
	//检查年龄是否合法
	private void checkAge(int age)throws AgeException {
		if(age<0 || age>260){
			throw new AgeException();
		}
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age)throws AgeException {
		checkAge(age);
		this.age = age;
	}
	public char getSex() {
		return sex;
	}
	public void setSex(char sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
}

(9)异常注意的问题

import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.transaction.xa.XAException;

public class ExceptionDemo9 {
	public static void main(String[] args) {
		
	}
}
class MyException extends ParseException{

	public MyException(String s, int errorOffset) {
		super(s, errorOffset);
		// TODO Auto-generated constructor stub
	}
}

class Father{
	public void test()throws ParseException{
		
	}
	
	public void test2()throws ParseException,FileNotFoundException,XAException{
		
	}
	public void run(){
		
	}
}
class Son extends Father{
	//子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类。
	@Override
	public void test() throws ParseException,MyException {
		
	}
	
	//如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或者它的子集,子类不能抛出父类没有的异常
	@Override
	public void test2() throws MyException {
		
	}
	
	//如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws
	@Override
	public void run() {
		try {
			new SimpleDateFormat().parse("");
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

十三、递归

//递归:就是方法体内调用方法自身的一种现象
public class DiGuiDemo {
	public static void main(String[] args) {
		method();//StackOverflowError
	}
	
	//构造方法不能递归
	public DiGuiDemo(){
		//DiGuiDemo();
	}

	//递归的次数不能太多,否则会内存溢出
	static int count = 100000;

	// 递归要有出口,不然就是死递归
	public static void method() {
		if (count-- > 0) {
			method();
		} else {
			return;
		}
	}
}

递归的实例

/*
 * 需求:求一个数值的阶乘
 * 	求5的阶乘:5*4*3*2*1
 * 如何定义一个递归?
 * 	规律:当前的阶乘等于自身值的值乘以自身值-1的数值阶乘
 * 	出口:1的阶乘就是1
 * 
 */
public class DiGuiDemo2 {
	public static void main(String[] args) {
		System.out.println(getResult(5));//120
	}
	
	/**
	 * 求对应数值的阶乘
	 * @param n
	 * @return
	 */
	public static int getResult(int n){
		//出口:1的阶乘就是1
		if(n==1){
			return 1;
		}else{
			//规律:当前的阶乘等于自身值的值乘以自身值-1的数值阶乘
			return n*getResult(n-1);
		}
	}
}

兔子问题(斐波那契数列)

/*
 * 兔子问题(斐波那契数列)
 * 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问第十个月的兔子对数为多少?
 * 
 * 一个月:一对
 * 二个月:一对
 * 三个月:二对
 * 四个月:三对
 * 五个月:五对
 * 六个月:八对
 * 
 * 规律:从第三个月开始的兔子对数等于前两个月兔子对数之和
 * 出口:当是一月份和二月份的时候,兔子对数是一
 */
public class DiGuiTest {
	public static void main(String[] args) {
		System.out.println(getSum(20));//55
	}
	
	/**
	 * 获取月份对应的兔子对数
	 * @param month
	 * @return
	 */
	public static int getSum(int month){
		//出口:当是一月份和二月份的时候,兔子对数是一
		if(1==month || 2==month){
			return 1;
		}else{
			//出口:当是一月份和二月份的时候,兔子对数是一
			return getSum(month-1)+getSum(month-2);
		}
	}
}

十四、File类

(1)定义

import java.io.File;

/*
 * 	File类的概述
		文件和目录路径名的抽象表示形式
	构造方法
		public File(String pathname)
		public File(String parent,String child)
		public File(File parent,String child)
 */
public class FileDemo {
	public static void main(String[] args) {
		String pathname = "E:/Test/bb/cc/修仙.txt";
		// public File(String pathname)通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例
		File file = new File(pathname );
		
		String parent = "E:/Test/bb/";
		String child = "cc/修仙.txt";
		// public File(String parent,String child)
		file = new File(parent, child);
		
		// public File(File parent,String child)
		file = new File(new File(parent),child);
	}
}
(2)创建功能
import java.io.File;

public class FileDemo2 {
	public static void main(String[] args) throws Exception {
		// 创建功能
		// public boolean createNewFile()创建一个新的标准文件,如果创建成功返回true
		File file = new File("D:/test.txt");
		System.out.println(file.createNewFile());
		 
		// public boolean mkdir()创建一个单级目录,如果创建成功返回true
		//file = new File("D:/aa");
		//System.out.println(file.mkdir());
		
		// public boolean mkdirs()创建多级目录,如果创建成功返回true
		file = new File("D:/aaa/bbb/ccc");
		System.out.println(file.mkdirs());
		
		// 删除功能
		// public boolean delete()只能删除空目录和标准文件
		//file = new File("D/aaa");
		//file = new File("D:/aa");
		//file = new File("D:/test.txt");
		//System.out.println(file.delete());
		
		
		// 重命名功能
		// public boolean renameTo(File dest)剪切并重命名
		file = new File("D:/test.txt");
		File dest = new File("E:/ttt.txt");
		System.out.println(file.renameTo(dest));
	}
}

(3)判断功能

import java.io.File;

public class FileDemo3 {
	public static void main(String[] args) {
		File file = new File("E:/ttt.txt");
		// public boolean isDirectory()判断此文件是否是目录
		System.out.println(file.isDirectory());//false
		// public boolean isFile()判断此文件是否是一个标准文件
		System.out.println(file.isFile());//true
		// public boolean exists()判断此文件是否存在
		System.out.println(file.exists());//true
		// public boolean canRead()判断此文件是否可读
		System.out.println(file.canRead());//true
		// public boolean canWrite()判断此文件是否可写
		System.out.println(file.canWrite());//true
		// public boolean isHidden()判断此文件是否隐藏
		System.out.println(file.isHidden());//false
	}
}

(4)获取功能

import java.io.File;

public class FileDemo3 {
	public static void main(String[] args) {
		File file = new File("E:/ttt.txt");
		// public boolean isDirectory()判断此文件是否是目录
		System.out.println(file.isDirectory());//false
		// public boolean isFile()判断此文件是否是一个标准文件
		System.out.println(file.isFile());//true
		// public boolean exists()判断此文件是否存在
		System.out.println(file.exists());//true
		// public boolean canRead()判断此文件是否可读
		System.out.println(file.canRead());//true
		// public boolean canWrite()判断此文件是否可写
		System.out.println(file.canWrite());//true
		// public boolean isHidden()判断此文件是否隐藏
		System.out.println(file.isHidden());//false
	}
}

面试题,file类

import java.io.File;
import java.io.FilenameFilter;

/*
 * 	判断单级目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
		研究用这个方法来做: File[] listFiles(FilenameFilter filter)
 */
public class FileTest {
	public static void main(String[] args) {
		method2();
	}

	private static void method2() {
		//1.将目标文件夹封装成File对象
		File file = new File("E:/Test");
		//2.使用过滤器过滤出指定后缀名的文件
		File[] files = file.listFiles(new FilenameFilter() {
			/*
			 * 	dir - 被找到的文件所在的目录。
				name - 文件的名称。
			 */
			@Override
			public boolean accept(File dir, String name) {
				//返回值的含义:当且仅当该名称应该包含在文件列表中时返回 true;否则返回 false。
				//如果当前的文件是一个标准文件且后缀名为.jpg返回true
				return new File(dir,name).isFile()?name.endsWith(".jpg"):false;
			}
		});
		//3.遍历文件
		for (File f : files) {
			System.out.println(f);
		}
	}

	private static void method1() {
		//1.将目标文件夹封装成File对象
		File file = new File("E:/Test");
		//2.获取文件夹底下所有的子文件对象
		File[] files = file.listFiles();
		//3.遍历每一个子文件,判断后缀名
		for (File f : files) {
			if(f.getAbsolutePath().endsWith(".jpg")){
				System.out.println(f.getAbsolutePath());
			}
		}
	}
}

递归底层原理图解



IO流业务逻辑图解



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值