头歌实训代码 Java面向对象 高级特性 多线程

Java实训代码、答案,如果能够帮到您,希望可以点个赞!!! 

如果有问题可以csdn私聊或评论!!!感谢您的支持

 

第五章 Java进阶 - 面向对象之类与对象

Java面向对象—类与对象

第一关:什么是类,如何创建类

package step1;

public class Test {
	public static void main(String[] args) {
		/********** Begin **********/
		//创建Dog对象
        Dog dog=new Dog();
		//设置Dog对象的属性
		dog.name="五花肉";
        dog.color="棕色";
        dog.pinzhong="阿拉斯加";
		
		//输出小狗的属性
		System.out.println("名字:" +dog.name+ ",毛色:" +dog.color+ ",品种:" +dog.pinzhong);
		
		//调用方法
        dog.eat();
        dog.play();

		
		/********** End **********/
		
	}
}

//在这里定义Dog类
class Dog{
    String name;
    String color;
    String pinzhong;
    void eat(){
        System.out.print("啃骨头\n");
    }
    void play(){
        System.out.print("叼着骨头跑\n");
    }

}

第二关:构造方法 

package step2;

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String name = sc.next();
		String sex = sc.next();
		/********** Begin **********/
		//分别使用两种构造器来创建Person对象  
		Person p1=new Person();
        Person p2=new Person(name,sex);

		/********** End **********/
		
	}
}

//创建Person对象,并创建两种构造方法
class Person{
    public Person(){
        super();
        System.out.println("一个人被创建了");
    }
    public Person(String name,String sex){
        super();
        System.out.println("姓名:"+name+",性别:"+sex+",被创建了");
    }

}

第三关: 选择题

  • 下列关于构造方法的说法不正确的是( C

    A、Java语言规定构造方法名必须与类名相同
    B、Java语言规定构造方法没有返回值,且不用void关键字声明
    C、构造方法不可以重载
    D、构造方法只能用new关键字来创建
  • 2、类Test定义如下:

     

    将下列哪些方法插入到第7行是合法的( CD )

    A、public float method1(){
    System.out.println("方法2"); return 1.1; }

    B、public Test1(){ System.out.println("hello"); }

    C、public float method1( int a){ System.out.println("方法2"); return a+0.5; }

    D、public Test(){ System.out.println("hello"); }

第四关:This关键字 

package step3;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String name = sc.next();
        int age = sc.nextInt();
        String sex = sc.next();
        Person p = new Person(name,age,sex);
        p.display();
    }
}

class Person{
    String name = "baby";
    int age = 45; 
    String sex = "女";
    /********** Begin **********/

    public Person(String name,int age,String sex){
        this(age);
        this.name = name;
        this.sex = sex;
    }
    
    public Person(int age){
        this.age = age;
    }
    
    public void display(){
        System.out.println("name:" + name);
        System.out.println("age:" + age);
        System.out.println("sex:" + sex);
    }
    /********** End **********/
}

第五关:类与对象练习 

package step4;
 
import java.util.Scanner;
 
public class Test {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String theMa = sc.next();
		int quantity = sc.nextInt();
		boolean likeSoup = sc.nextBoolean();
		/********** Begin **********/
		//使用三个参数的构造方法创建WuMingFen对象  取名 f1
        WuMingFen f1=new WuMingFen(theMa,quantity,likeSoup);
		//使用两个参数的构造方法创建WuMingFen对象  取名 f2
        WuMingFen f2=new WuMingFen(theMa,quantity);
		//使用无参构造方法创建WuMingFen对象  取名 f3
        WuMingFen f3=new WuMingFen();
		//分别调用三个类的 check方法
        f1.cheak();
        f2.cheak();
        f3.cheak();
 
		
		/********** End **********/	
	}
}
class WuMingFen{
    String theMa;
    int quantity;
    boolean likeSoup;
    public WuMingFen(String theMa,int quantity){
        this.theMa=theMa;
        this.quantity=quantity;
    }
    public WuMingFen(String theMa,int quantity,boolean likeSoup){
        this.theMa=theMa;
        this.quantity=quantity;
        this.likeSoup=likeSoup;
    }
    public WuMingFen(){
        theMa="酸辣";
        quantity=2;
        likeSoup=true;
    }
    public void cheak(){
        System.out.println("面码:"+this.theMa+",粉的份量:"+this.quantity+"两,是否带汤:"+this.likeSoup);
    }
}

第六关:static关键字 

package step5;
public class Test {
	/********** Begin **********/
	static String name = "楚留香";
	static
	{
		System.out.println("hello educoder");
	}
	public static void main(String[] args) {
		System.out.println("我叫" + name);
		study();
	}
	
	public static void study(){
		System.out.println("我喜欢在educoder上学习java");
	}
	/********** End **********/
}

第七关:选择题 

  • 有如下代码:

    public class TestMain{
        public static void main(String args[]){
        MyClass mc1 = new MyClass();
        MyClass mc2 = new MyClass();
        mc1.a = 100;
        mc1.b = 200;
        mc2.a = 300;
        mc2.b = 400;
        System.out.println(mc1.a);
        System.out.println(mc1.b);
        System.out.println(mc2.a);
        System.out.println(mc2.b);
        }
    }
    class MyClass{
        static int a;
        int b;
    }

    请问输出结果是( D

    A、100 100 100 100

    B、100 200 300 400

    C、400 400 400 400

    D、300 200 300 400

  • 2、

    class MyClass {
        int a;
        static int b;
        void fa(){
        
        }
        static void fb(){
        
        }
        public void m1(){
            System.out.println(a);    //位置1
            System.out.println(b);    //位置2
            fa();                     //位置3
            fb();                     //位置4
        }
        public static void m2(){
            System.out.println(a);    //位置5
            System.out.println(b);    //位置6
            fa();                    //位置7
            fb();                    //位置8
        }
    }

    上述代码会出错的位置有:( EG

    A、位置1
    B、位置2
    C、位置3
    D、位置4
    E、位置5
    F、位置6
    G、位置7
  • 3、

    class MyClass {
        static int i = 10;
        static {
            i = 20;
            System.out.println("In Static");
        }
        public MyClass() {
            System.out.println("MyClass()");
        }
        public MyClass(int i) {
            System.out.println("MyClass(int)");
            this.i = i;
        }
    }
    public class TestMain {
        public static void main(String args[]) {
            MyClass mc1 = new MyClass();
            System.out.println(mc1.i);
            MyClass mc2 = new MyClass(10);
            System.out.println(mc2.i);
        }
    }

    上述代码的运行结果是:( B

    A、MyClass() 20 MyClass(int) 10
    B、In Static MyClass() 20 MyClass(int) 10
    C、In Static MyClass(int) 20 MyClass() 10
    D、In Static MyClass() 10 MyClass(int) 20

Java面向对象—封装、继承和多态 

第一关:什么是封装,如何使用封装

package case1;
 
public class TestPersonDemo {
	public static void main(String[] args) {
		/********* begin *********/
		// 声明并实例化一Person对象p
		Person p = new Person();
 
		// 给p中的属性赋值
		p.setName("张三");
		p.setAge("18岁");
 
		// 调用Person类中的talk()方法
		p.talk();
 
		/********* end *********/
 
	}
}
 
// 在这里定义Person类
class Person {
	/********* begin *********/
	private String name;
	private String age;
	public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getAge(){
        return age;
    }
    public void setAge(String age){
        this.age = age;
    }
	public void talk(){
		System.out.print("我是:"+name+",今年:"+age);
	}
	/********* end *********/
}

第二关:什么是继承,怎样使用继承 

package case2;
 
public class extendsTest {
	public static void main(String args[]) {
		// 实例化一个Cat对象,设置属性name和age,调用voice()和eat()方法,再打印出名字和年龄信息
		/********* begin *********/
		Cat c=new Cat("大花猫",6);
		c.voice("大花猫");
		c.eat("大花猫");
		System.out.println(c.getName()+c.getAge()+"岁");
 
		/********* end *********/
 
		// 实例化一个Dog对象,设置属性name和age,调用voice()和eat()方法,再打印出名字和年龄信息
		/********* begin *********/
		Dog d=new Dog("大黑狗",8);
		d.voice("大黑狗");
		d.eat("大黑狗");
		System.out.println(d.getName()+d.getAge()+"岁");
 
		/********* end *********/
 
	}
}
 
class Animal {
	/********* begin *********/
	private String name;
	private int age;
	public Animal(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 getAge(){
		return age;
	}
	public void setAge(int age){
		this.age = age;
	}
 
	/********* end *********/
 
}
 
class Cat extends Animal {
	// 定义Cat类的voice()和eat()方法
	/********* begin *********/
	public Cat(String name,int age){
		super(name,age);
	}
	public void voice(String name){
	    System.out.println(name+"喵喵叫");
	}
	public void eat(String name){
		System.out.println(name+"吃鱼");
	}
 
	/********* end *********/
}
 
class Dog extends Animal {
	// 定义Dog类的voice()和eat()方法
	/********* begin *********/
	public Dog(String name,int age){
		super(name,age);
	}
	public void voice(String name){
	    System.out.println(name+"汪汪叫");
	}
	public void eat(String name){
		System.out.println(name+"吃骨头");
	}
 
	/********* end *********/
}

第三关:super关键字的使用 

package case3;
 
public class superTest {
	public static void main(String[] args) {
		// 实例化一个Student类的对象s,为Student对象s中的school赋值,打印输出信息
		/********* begin *********/
		Student s = new Student();
		s.school = "哈佛大学";
		System.out.println("姓名:"+s.name+",年龄:"+s.age+",学校:"+s.school);
 
		/********* end *********/
	}
}
 
class Person {
	/********* begin *********/
    String name;
    int age;
	public Person(String name,int age){
		this.name=name;
		this.age=age;
	}
 
	/********* end *********/
}
 
class Student extends Person {
	/********* begin *********/
	String school;
	public Student(){
		super("张三",18); //super调用父类的方法
	}
 
	/********* end *********/
}

第四关:方法的重写与重载 

package case4;
 
public class overridingTest {
	public static void main(String[] args) {
		// 实例化子类对象s,调用talk()方法打印信息
		/********* begin *********/
		Student s=new Student("张三",18,"哈佛大学");
        s.talk();
 
		/********* end *********/
		
	}
}
 
class Person {
	/********* begin *********/
	String name;
	int age;
	public void talk(){
		System.out.println("我是:"+name+"今年:"+age+"岁");
	}
 
	/********* end *********/
}
 
class Student extends Person {
	/********* begin *********/
	String school;
	Student(String name,int age,String school){
        this.name=name;
        this.age=age;
        this.school=school;
    }
    public  void talk(){
        System.out.print("我是:"+name+","+"今年:"+age+"岁"+","+"我在"+school+"上学");
    }
	/********* end *********/
}

第五关:抽象类 

package case5;
 
public class abstractTest {
	public static void main(String[] args) {
		/********* begin *********/
		// 分别实例化Student类与Worker类的对象,并调用各自构造方法初始化类属性。
		Student s=new Student("张三",20,"学生");
        Worker w=new Worker("李四",30,"工人");
		// 分别调用各自类中被复写的talk()方 印息
	    s.talk();
        w.talk();
		/********* end *********/
		
	}
}
 
// 声明一个名为Person的抽象类,在Person中声明了三个属性name age occupation和一个抽象方法——talk()。
abstract class Person {
	/********* begin *********/
    String name;
    int age;
    String occupation;
    abstract void talk();
	/********* end *********/
}
 
// Student类继承自Person类,添加带三个参数的构造方法,复写talk()方法 返回姓名、年龄和职业信息
class Student extends Person {
	/********* begin *********/
    public Student(String name,int age,String occupation){
        this.name=name;
        this.age=age;
        this.occupation=occupation;
    }
    public void talk(){
        System.out.println("学生——>姓名:"+this.name+","+"年龄:"+this.age+","+"职业:"+this.occupation+"!");
    }
	/********* end *********/
}
 
// Worker类继承自Person类,添加带三个参数的构造方法,复写talk()方法 返回姓名、年龄和职业信息
class Worker extends Person {
	/********* begin *********/
    public Worker(String name,int age,String occupation){
        this.name=name;
        this.age=age;
        this.occupation=occupation;
    }
    public void talk(){
        System.out.println("工人——>姓名:"+this.name+","+"年龄:"+this.age+","+"职业:"+this.occupation+"!");
    }
	/********* end *********/
}

第六关:final关键字的理解和使用 

package case6;
 
public class finalTest {
	public static void main(String args[]) {
		Bike1 obj = new Bike1();
		obj.run();
 
		Honda honda = new Honda();
		honda.run();
 
		Yamaha yamaha = new Yamaha();
		yamaha.run();
	}
}
//不可以修改 final 变量的值
// final方法,不可以重写
//不可以扩展 final 类
    //请在此添加你的代码
    /********** Begin *********/
	class Bike1 {
    int speedlimit = 90;
 
	void run() {
		speedlimit = 120; 
		System.out.println("speedlimit=120");
	}
 
}
 
class Bike2 {
	 void run() {
		System.out.println("running");
	}
}
 
class Honda extends Bike2 {
	void run() { 
		System.out.println("running safely with 100kmph");
	}
 
}
 
class Bike3 {
}
 
class Yamaha extends Bike3 { 
	void run() {
		System.out.println("running safely with 100kmph");
	}
 
}

第七关:接口 

package case7;
 
public class interfaceTest {
	public static void main(String[] args) {
		// 实例化一Student的对象s,并调用talk()方法,打印信息
		/********* begin *********/
        Student s=new Student();
        System.out.println(s.talk());
		/********* end *********/
 
	}
}
 
// 声明一个Person接口,并在里面声明三个常量:name、age和occupation,并分别赋值,声明一抽象方法talk()
interface Person {
	/********* begin *********/
    final String name="张三";
    final int age=18;
    final String occupation="学生";
    abstract String talk();
	/********* end *********/
}
 
// Student类继承自Person类 复写talk()方法返回姓名、年龄和职业信息
class Student implements Person {
	/********* begin *********/
    public String talk(){
        return "学生——>姓名:"+this.name+","+"年龄:"+this.age+","+"职业:"+this.occupation+"!";
    }
	/********* end *********/
}

第八关:什么是多态,怎样使用多态 

package case8;
 
public class TestPolymorphism {
	public static void main(String[] args) {
		// 以多态方式分别实例化子类对象并调用eat()方法
		/********* begin *********/
    Animal dog=new Dog();
    dog.eat();
    Animal cat=new Cat();
    cat.eat();
    Animal lion=new Lion();
    lion.eat();
		/********* end *********/
	}
}
 
// Animal类中定义eat()方法
class Animal {
	/********* begin *********/
public void eat(){
    
}
	/********* end *********/
}
 
// Dog类继承Animal类 复写eat()方法
class Dog extends Animal {
	/********* begin *********/
public void eat(){
    System.out.println("eating bread...");
}
	/********* end *********/
}
 
// Cat类继承Animal类 复写eat()方法
class Cat extends Animal {
	/********* begin *********/
public void eat(){
    System.out.println("eating rat...");
}
	/********* end *********/
}
 
// Lion类继承Animal类 复写eat()方法
class Lion extends Animal {
	/********* begin *********/
public void eat(){
    System.out.println("eating meat...");
}
	/********* end *********/
}

第六章 Java进阶 - 面向对象之常用类 

Java面向对象—String类

第一关:length()方法与compareTo()方法的使用 - 花名册

package step1;
import java.util.Scanner;
public class Roster {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        /********** Begin *********/
    String s1=scanner.nextLine();
    String s2=scanner.nextLine();
    System.out.println(s1.length());
    System.out.println(s2.length());
    int a=s1.compareTo(s2);
    if(a!=0)
        System.out.println("不相同");
    else
        System.out.println("相同");
 
 
        /********** End *********/
    }
}

第二关:substring()方法与indexOf()方法的使用 - 姓名

package step2;
import java.util.Scanner;
public class NameSearch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        /********** Begin *********/
    String date=scanner.nextLine();
    String name=scanner.nextLine();
    int i=0,a=0;
    while(i<=date.length()){
        a=date.indexOf(name,i);
        if(a!=-1){
            System.out.println(a);
            i=a+1;
        }
        else
            i++;
    }
 
        /********** End *********/
    }
}

第三关:String串类操作 - 文件名与邮箱验证

package step3;
public class HelloWorld {
	public void judge(String fileName,String email){
		//请在此添加实现代码
/********** Begin **********/
int a1=fileName.indexOf(".java");
int a2=fileName.lastIndexOf(".java");
if( a1!=-1 && a1!=0 && a2==fileName.length()-5)
    System.out.println("Java文件名正确");
else
    System.out.println("Java文件名无效");
 
int b1=email.indexOf(".com");
if(b1!=-1 && b1!=0)
    System.out.println("邮箱名正确");
else
    System.out.println("邮箱名无效");
 
/********** End **********/
	}	
}

第四关:StringBuffer类的定义和使用 - 字母反转 

package step4;
public class Reverse {
    public static StringBuffer start(String data) {
        StringBuffer ans = new StringBuffer();
        /********** Begin *********/
    String[] strings = data.split(" ");
    for(int i=0;i<strings.length;i++){
        StringBuffer stringBuffer=new StringBuffer(strings[i]);
        ans.append(stringBuffer.reverse());
        ans.append(" ");
    }
 
        /********** End *********/
        return ans;
    }
}

Java面向对象—包装类 

第一关:基本数据类型和包装类之间的转换

package step1;

public class Task {
	public static void main(String[] args) {
		
		//请在此添加实现代码
		/********** Begin **********/
		//定义float对象
		float f = 66.6f;
		
		//手动装箱
		Float f1 = new Float(f);
		
		//自动装箱 
		Float f2 =f;
		
		System.out.println("装箱后的结果为:" + f1 + "和" + f2);
		
		//定义一个Double包装类值为88.88
		Double d = new Double(88.88);
		
		//手动拆箱
		double d1 = d.doubleValue();
		
		//自动拆箱
		double d2 = d;
		
		System.out.println("拆箱结果为:" + d1 + "和" + d2);
		
		/********** End **********/
		
	}

}

第二关:包装类转换成其他数据类型 

package step2;

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

		//请在此添加实现代码
		/********** Begin **********/
		// 定义int类型变量,值为67
		int score = 67;

		// 创建Integer包装类对象,表示变量score的值
		Integer score1 = new Integer(score);

		// 将Integer包装类转换为double类型
		double score2 = score1.doubleValue(); 

		// 将Integer包装类转换为float类型
		float score3 = score1.floatValue();

		// 将Integer包装类转换为int类型
		int score4 = score1.intValue();

		System.out.println("Integer包装类:" + score1);
		System.out.println("double类型:" + score2);
		System.out.println("float类型:" + score3);
		System.out.println("int类型:" + score4);

		/********** End **********/
		
	}
}

第三关:包装类与字符串之间的转换 

package step3;

public class Task {
	public static void main(String[] args) {
		double a = 78.5;
        
		//请在此添加实现代码
		/********** Begin **********/
		//将基本类型a转换为字符串
		String str = String.valueOf(a);
        
		System.out.println("str + 12  的结果为: "+(str + 12));
		
		String str1 = "180.20";
	    // 将字符串str1转换为基本类型
		Double d = Double.parseDouble(str1);
	
		System.out.println("d + 100 的结果为: "+ (d + 100));

		/********** End **********/
		
	} 
}

Java面向对象—常用类 

第一关:Object类

package case1;

import java.util.Scanner;

public class ObjectTest {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int num1 = sc.nextInt();
		int num2 = sc.nextInt();
		// 在测试类中创建Demo类对象d1,传入输入值num1, d1调用toString方法并打印输出该值
		// 创建Demo类对象d2,同样传入输入值num1,打印判断d1和d2是否相等(实际是比较地址)
		/********* Begin *********/
		Demo d1=new Demo(num1);
		System.out.println(d1.toString());
		Demo d2=new Demo(num1);
		if (d1.equals(d2)) {
            System.out.println("true");
        } else {
            System.out.println("false");
        }
		/********* End *********/
		// 创建Person类对象p,传入输入值num2,打印判断d1和p是否相等(实际是比较地址)
		/********* Begin *********/
		Person p=new Person(num2);
		if (d1.equals(p)) {
            System.out.println("true");
        } else {
            System.out.println("false");
        }
		/********* End *********/
	}
}

class Demo {
	private int num;

	public Demo(int num) {
		this.num = num;
	}

	public boolean equals(Object obj) // Object obj = new Demo()
	{
		if (!(obj instanceof Demo)) // 判断obj是否和Demo是同类
			return false;
		Demo d = (Demo) obj; // 将父类的引用(Object)向下转换为子类(Demo)
		return this.num == d.num;
	}

	public String toString() {
		return "Demo:" + num; // 返回对象的值(每一个对象都有自己的特定的字符串)
	}
}

class Person {
	private int num;

	public Person(int num) {
		this.num = num;
	}
}

第二关:Java基础类型包装类 - 练习

package case2;

import java.util.Scanner;

public class WrapperTest {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int aa = sc.nextInt();
		String bb = sc.next();
		int c = sc.nextInt();
		String str11 = sc.next();
		String str22 = sc.next();
		// 包装类中“==”与equals的用法比较
		// 值得注意的是,包装类中的equals方法和String类一样,都是重写了Object类中的equals方法,因此比较的是内容而不是地址,
		// 而“==”比较的依然是引用变量的地址,只是当包装类型和与之相对应的基本类型进行“==”比较时会先做自动拆箱处理。
		/********* Begin *********/
		Integer a=new Integer(aa);
		Integer b=Integer.parseInt(bb);
		String str1=new String(str11);
		String str2=new String(str22);
		System.out.println(a==b);
		System.out.println(a==c);
		System.out.println(b==c);
		System.out.println(a.equals(b));
		System.out.println(str1==str2);
		System.out.println(str1.equals(str2));
		/********* End *********/
	}
}

第三关:String&StringBuilder&StringBuffer类-练习 

package case3;

import java.util.Scanner;

public class StringTest {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str = sc.next();
		// String substring(int start,int end)
		// 截取字符串,传入的两个参数分别为要截取边界的下标
		// 在java api 中,通常使用两个数字表示范围时,都是含头不含尾,即包含起始下标对应的内容,但不包含结束下标的处对应的内容
		// String toUpperCase() 将当前字符串中的英文部分转换为全大写
		/********* Begin *********/
		String str1=str.substring(12,str.lastIndexOf('.'));
		if(str1.indexOf('.')>0){
			str1=str1.substring(0,str1.indexOf('.'));
		}
		System.out.println(str1);
		str1=str1.toUpperCase();
		System.out.println(str1);
		/********* End *********/
	}
}

第四关:Random类 

package case4;

//密码的自动生成器:密码由大写字母/小写字母/数字组成,生成六位随机密码
import java.util.Random;
import java.util.Scanner;

public class RandomTest {
	public static void main(String[] args) {
		// 定义一个字符型数组
		char[] pardStore = new char[62];
		// 把所有的大写字母放进去 把所有的小写字母放进去 把0到9放进去
		/********* Begin *********/
		for(int i=0;i<26;i++)
		{
			pardStore[i]=(char)('A'+i);
			pardStore[26+i]=(char)('a'+i);
		}
		for(int i=0;i<10;i++)
		{
			pardStore[52+i]= (char)('0' + i);
		}
		/********* End *********/
		// 分别以1、2、3作为种子数 生成6位随机密码
		Scanner sc = new Scanner(System.in);
		int seed = sc.nextInt();
		/********* Begin *********/
		Random r=new Random(seed);
		String str="";
		int[] arr=r.ints(6,0,62).toArray();
		for(int i=0;i<6;i++)
		{
			str+=pardStore[arr[i]];
		}
		System.out.print(str);
		/********* End *********/
	}
}

第五关:Date类和SimpleDateFormat类的用法 

package case5;

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

public class DateTest {
	public static void main(String[] args) throws ParseException {
		// 键盘录入你的出生年月日 格式为yyyy-MM-dd
		// 把该字符串转换为一个日期
		// 通过该日期得到一个毫秒值
		// 获取2020年10月1日的毫秒值
		// 两者想减得到一个毫秒值
		// 把该毫秒值转换为天 打印输出
		Scanner sc = new Scanner(System.in);
		String line = sc.nextLine();
		/********* Begin *********/
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Date d1=sdf.parse(line);
		Date d2=sdf.parse("2020-10-01");
		long diff=d2.getTime()-d1.getTime();
		diff=diff/86400000;
		System.out.println("你的出生日期距离2020年10月1日:"+diff+"天");
		/********* End *********/
	}
}

第六关:Math类 

package case6;

import java.util.Scanner;
import java.lang.Math;

public class MathTest {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a1 = sc.nextInt();
		int a2 = sc.nextInt();
		int a3 = sc.nextInt();
		int a4 = sc.nextInt();
		double a5 = sc.nextDouble();
		double a6 = sc.nextDouble();
		double a7 = sc.nextDouble();
		double a8 = sc.nextDouble();
		double a9 = sc.nextDouble();
		double a10 = sc.nextDouble();
		double a11 = sc.nextDouble();
		/********* Begin *********/
		System.out.println(Math.sqrt(a1));
		System.out.println(Math.cbrt(a2));
		System.out.println(Math.pow(a3,a4));
		System.out.println(Math.max(a5,a6));
		System.out.println(Math.min(a5,a6));
		System.out.println(Math.abs(a7));
		System.out.println(Math.ceil(a8));
		System.out.println(Math.floor(a9));
		System.out.println(Math.rint(a10));
		System.out.println(Math.round(a11));
		/********* End *********/
	}
}

第七章 Java进阶 - 面向对象之异常与文件类

Java面向对象—Java中的异常

第一关:Java中的异常处理机制

  • 在Java中,源文件Test.java中包含如下代码段,则程序编译运行结果是( B

    public class HelloWorld{
        public static void main(String[] args){
            System.out.print(“HelloWorld!”);
        }
    }

    A、输出:HelloWorld!
    B、编译出错,提示“公有类HelloWorld必须在HelloWorld.java文件中定义”
    C、运行正常,但没有输出内容
    D、运行时出现异常

  • 2、下列关于检测性异常和非检测性异常正确的是( ACE

    A、IOException及其子类(FileNotFoundException等),都属于检测型异常
    B、检测型异常不需要程序员来处理
    C、运行时异常可以处理,也可以不处理,是可选的
    D、错误也属于异常的一种
    E、所有的异常类是从 java.lang.Exception 类继承的子类
  • 3、关于下列代码,说法正确的是( D

    public static void main(String[] args){
        int num1 = 10;
        int num2 = 0;
        System.out.println(num1/num2);
    }

    A、输出0
    B、编译报错,提示除数不能为0
    C、输出无穷大
    D、运行时报错,提示除数不能为0

第二关:捕获异常 

package step2;
import java.util.Scanner;
public class Task {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int num1 = sc.nextInt();
		int num2 = sc.nextInt();
		/********* Begin *********/
		 try{
		System.out.println(num1/num2);}
		catch(ArithmeticException e){
          System.out.print("除数不能为0");
		}	
		/********* End *********/
	}
}

第三关:抛出异常 

package step3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Task {
	public static void main(String[] args)throws FileNotFoundException{	
		test();
	}
	public static void test()throws FileNotFoundException{
		File file = new File("abc");
		if(!file.exists()){		//判断文件是否存在
			//文件不存在,则 抛出 文件不存在异常
			throw new FileNotFoundException("该文件不存在");
		}else{
			FileInputStream fs = new FileInputStream(file);
		}
	}
	/********* End *********/
}

第四关:自定义异常 

package step4;
import java.util.Scanner;
public class Task {
	/********* Begin *********/
	public static void main(String[] args)throws MyException {
		Scanner sc = new Scanner(System.in);
		String username = sc.next();
		//判断用户名
		if(username.length()<3){
			throw new MyException("用户名小于三位Exception");
		}
		else{
			System.out.println("用户名格式正确");
		}
	}
}
class MyException extends Exception{
	public MyException(){}
	public MyException(String msg){
		super(msg);
	}
}

Java面向对象—文件类 

第一关:创建文件

package step1;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Scanner;

public class Task {
	/********* Begin *********/
	public void solution() throws IOException       {
		try {
			File file1 = new File("src/output/hello.txt");
			File file2 = new File("src/output/test.txt");
			file1.createNewFile();
			file2.createNewFile();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
		
		
		/********* End *********/
}

第二关:文件的常用操作 

package step2;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Arrays;


public class Task {
	public static void dcFile() throws IOException {
		/********* Begin *********/
		File file0=new File("src/test2");
		file0.mkdir();
        File file1=new File("src/output/test2.txt");
        file1.delete();
File file2 = new File("src/output");
File file3=new File("src/test2/helloworld.txt");
File file4=new File("src/test2/step2.txt");
file3.createNewFile();
file4.createNewFile();
File[] files5=file0.listFiles();
Arrays.sort(files5);
File[] files6=file2.listFiles();
Arrays.sort(files6);
System.out.println("output目录结构为:");
for(File file :files6){
	System.out.println(file.getName());
}
		
System.out.println("test2目录结构为:");
for(File file:files5){
	System.out.println(file.getName());
}


		
		



		/********* End *********/
	}
}

第三关:文件查看器 

package step3;

import java.io.File;
import java.util.Arrays;

public class Task {
	
	/********** Begin **********/
	public void showDirStructure(File file)	{
		System.out.println("+--"+file.getName());
		showDirTree(file," ");
	}
	public static void showDirTree(File dir,String interval){
		File[] files=dir.listFiles();
		Arrays.sort(files);
		interval+=" ";
		for(File file:files){
			if(!file.isDirectory()){
				System.out.println(interval+"--"+file.getName());
			}
			else{
				System.out.println(interval+"+--"+file.getName());
				showDirTree(file,interval+" ");
			}
		}
	}
	
	


	/********** End **********/
}

第四关:图片查看器 

package step4;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
public class Task {
	
	/********** Begin **********/
	public void showDirStructure(File file)	{
		if(file.isDirectory()){
			System.out.println("+--"+file.getName());	
		}
		int Blank= 2;
		showDir(file,Blank);
	}

	public static void showDir(File file,int Blank){
		File[] files=file.listFiles();
		Arrays.sort(files);
		for(int i=0;i<files.length;i++){
			if(files[i].isDirectory()){
				for (int k = 0; k < Blank; k++){
					System.out.print(" ");
				}
				System.out.println("+--" + files[i].getName());
				showDir(files[i], Blank+2);
			}
			else{
				int end =  files[i].toString().indexOf(".");
				String suffix = files[i].toString().substring(end+1);
				if(suffix.equals("jpg") || suffix.equals("png") || suffix.equals("bmp")){
					for (int k = 0; k < Blank; k++){
						System.out.print(" ");
					}
					System.out.println("--" + files[i].getName());
				}
			}
		}






	}
	

	/********** End **********/
}

第八章 Java高级特性 

Java高级特性—集合框架

第一关:集合的基本使用 

package step1;
import java.util.ArrayList;        //导包
public class HelloWorld {
    public ArrayList getList() {
        /********** Begin **********/
        ArrayList list = new ArrayList();
        list.add("https:www.educoder.net");
           list.add(2018.423);
        return list;
        /********** End **********/
    }
}

第二关:ArrayList集合的增删改查 

package step2;
import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld {
    public static void main(String[] args) {
        //获取输入的数据并添加至集合
        Scanner sc = new Scanner(System.in);
        ArrayList list = new ArrayList<>();
        int length = sc.nextInt();
        for(int i =0 ; i< length ;i++){
            list.add(sc.next());
        }
        /********** Begin *********/
        list.remove(0);                //删除第一个元素
        list.remove(list.size()-1); //删除最后一个元素
        list.add("hello");            //添加
        list.add("educoder");
        list.set(2,"list");            //修改
        //输出list中所有的数据
        for(int i = 0 ; i< list.size(); i++){
            System.out.println(list.get(i));
        }
        /********** End **********/
    }
}

第三关:集合的体系结构 

package step3;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class HelloWorld {
    public HashSet getHashSet(){
        /********** Begin **********/
        HashSet set = new HashSet();
        set.add("www.educoder.net");
        return set;
        /********** End **********/
    }
    public ArrayList getArrayList(){
        /********** Begin **********/
        ArrayList list = new ArrayList();
        list.add("www.educoder.net");
        return list;
        /********** End **********/
    }
    public LinkedList getLinkedList(){
        /********** Begin **********/
        LinkedList list = new LinkedList();
        list.add("www.educoder.net");
        return list;
        /********** End **********/
    }
    public Map getHashMap(){
        /********** Begin **********/
        Map map = new HashMap();
        map.put("address","www.educoder.net");
        return map;
        /********** End **********/
    }    
}

第四关:泛型 

package step4;
import java.util.*;
public class HelloWorld {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //程序会输入三次数据
        /********** Begin **********/
        List<String> list = new ArrayList<String>();
        for(int i = 0 ; i< 3;i++){
            list.add(sc.next());
        }
        for(int i = 0 ; i< 3;i++){
            System.out.println("集合的第" + (i+1) + "个数据为:" + list.get(i));
        }
        /********** End **********/
    }
}

第五关:Map集合的增删改查 

package step5;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class HelloWorld {
    public static void main(String[] args) {
        Map<String, Integer> menuDict = new HashMap<>();
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 5; i++) {
            menuDict.put(sc.next(),sc.nextInt());
        }
        /********** Begin **********/
        menuDict.put("lamb",50);
        System.out.println(menuDict.get("fish"));
        menuDict.put("fish",100);
        menuDict.remove("noodles");
        System.out.println(menuDict.toString());
        /********** End **********/
    }
}

 第六关:选择题

在Java中,以下( B )类的对象以键值对(key-value)的方式存储对象

A、java.util.List

B、java.util.ArrayList

C、java.util.HashMap

D、java.util.LinkedList

Java高级特性—IO流 

第一关:什么是IO流

  • 1、下列关于字节和字符的说法正确的是( BC

    A、字节 = 字符 + 编码
    B、字符 = 字节 + 编码
    C、字节 = 字符 + 解码
    D、字符 = 字节 + 解码
  • 2、下列描述正确的是:( C

    A、使用代码读取一个文件的数据时,应该使用输出流。
    B、使用代码复制文件的时候,只需要使用输出流。
    C、使用代码读取一个文本文件的数据时,只需要使用输入流即可。
    D、从客户端向服务端发送数据可以使用输入流。

第二关:字节流 - 输入输出 

package step2;
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;
public class Task {
	public void task() throws IOException{
		/********* Begin *********/
		File file = new File("src/step2/input/task.txt");
		FileInputStream fs = new FileInputStream(file);  //定义一个文件输入流
		byte[] b = new byte[8];                         //定义一个字节数组
		fs.read(b);                                     //将输入流的数据读入到字节数组
		String str = new String(b,"UTF-8");             //通过utf-8编码表将字节转换成字符
		System.out.println(str);
		File dir = new File("src/step2/output");
		if(!dir.exists()){
			dir.mkdir();
		}
		FileOutputStream out = new FileOutputStream("src/step2/output/output.txt"); //创建输出流
		String str1 = "learning practice";
		byte[] c = str1.getBytes();   //将字符串转换成字节
		out.write(c);                 //写数据
		out.flush();                  //刷新缓存区数据
		fs.close();					  //释放资源
		out.close();
		/********* End *********/
	}
}

第三关:字符流 - 输入输出 

package step3;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Task {
	public void task() throws IOException{
		/********* Begin *********/
		String file1 = "src/step3/input/input.txt";
		FileReader fr = new FileReader(file1);
		char[] ch = new char[8];
		fr.read(ch);
		String file2 = "src/step3/output/output.txt";
		FileWriter fw = new FileWriter(file2);
		fw.write(ch);
		fr.close();
		fw.flush();
		fw.close();
		/********* End *********/		
	}
}

第四关 :复制文件

package step4;

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

public class Task {
	
	public void task() throws IOException{
		/********* Begin *********/
		String file1 = "src/step4/input/input.txt";
		FileInputStream fr = new FileInputStream(file1);
		byte[] b = new byte[1024];
		int len = 0;

		String file2 = "src/step4/output/output.txt";
		FileOutputStream fw = new FileOutputStream(file2);
		while((len = fr.read(b))!=-1){
			fw.write(b,0,len);
		}
		fr.close();
		fw.close();

		String file3 = "src/step4/input/input.jpg";
		String file4 = "src/step4/output/output.jpg";
		FileInputStream fs = new FileInputStream(file3); //定义文件输入流读取文件信息
		FileOutputStream fos = new FileOutputStream(file4);//定义文件输出流写文件
		len = 0;        //每次读取数据的长度
		byte[] bys = new byte[1024];    //数据缓冲区
		while( (len = fs.read(bys)) != -1){
			fos.write(bys, 0, len);
		}
		//释放资源  刷新缓冲区
		fs.close();
		fos.close();
		/********* End *********/		
	}
}


第八章 Java多线程 

Java高级—多线程

第一关:创建多线程


package step1;
 
public class CreateThreadPractice {
 
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        // ---------------------Begin------------------------
        //开启线程
        myThread.start();
 
        // ---------------------End------------------------
    }
}
// ---------------------Begin------------------------
//继承Thread编写名为MyThead的类,代码内容为循环输出10遍: 线程在运行......
 
class MyThread extends Thread{
    public  void run()
    {
       for(int i=0;i<10;i++) System.out.println("线程在运行......");
    }
}
 
 
// ---------------------End------------------------

第二关: 使用Callable接口创建多线程

package step2;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
// ---------------------Begin------------------------
//tips: 输出语句为:Thread.currentThread().getName()+"的call()方法在运行"
//定义一个实现Callable接口的实现类,类名必须命名为MyThread_callable
 
// ---------------------End------------------------
public class CallableExample {
    public static void main(String[] args) throws Exception,
            ExecutionException {
        // 创建Callable接口的实现类对象
        MyThread_callable myThread3 = new MyThread_callable();
        // 使用FutureTask封装Callable接口
        FutureTask<Object> ft1 = new FutureTask<>(myThread3);
        // 使用Thread(Runnable target ,String name)构造方法创建线程对象
        Thread thread1 = new Thread(ft1, "thread1");
        // 创建并启动另一个线程thread2
        FutureTask<Object> ft2 = new FutureTask<>(myThread3);
        Thread thread2 = new Thread(ft2, "thread2");
        // ---------------------Begin------------------------
        // 调用线程对象的start()方法启动线程
        thread1.start();
        Thread.sleep(1000);
        thread2.start();    
        Thread.sleep(1000);
        // 可以通过FutureTask对象的方法管理返回值
        System.out.println("thread1返回结果:"+ft1.get());
        System.out.println("thread2返回结果:"+ft2.get());
        // ---------------------End------------------------
    }
    
}
class MyThread_callable implements Callable<Object>{
    // @Override
    public Object call() throws Exception{
        for(int i=0;i<5;i++) System.out.println(Thread.currentThread().getName()+"的call()方法在运行");
        return Thread.currentThread().getName();
    }
}

第三关:使用Runable接口创建多线程 

package step3;
// ---------------------Begin------------------------
//定义一个实现Runnable接口的实现类,类名必须命名为MyThread_runable
//tips: 输出语句为:Thread.currentThread().getName()+"的run()方法在运行"
class MyThread_runable implements Runnable{
    @Override
    public void run(){
        for(int i=0;i<3;i++) System.out.println(Thread.currentThread().getName()+"的run()方法在运行");
    }
}
 

// ---------------------End------------------------

第四关:多线程中的售票问题 

package step4;
 
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public class SellTicket extends Thread {
    //多线程共享资源,票数为30张
    private static ReentrantLock lock = new ReentrantLock();
	private static int ticket = 30;
 
	@Override
	public void run() {
 
		while (true) {
			try {
				lock.lock();
 
				if (ticket > 0) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e1) {
						// TODO 自动生成的 catch 块
						e1.printStackTrace();
					}
					System.out.println("卖出了第" + ticket + "张票");
					ticket--;
				} else {
					System.out.println("票卖完了");
					System.exit(0);
				}
 
			} finally {
 
				lock.unlock();
 
			}
 
		}
    
    // ---------------------End------------------------
}
 
}
/********* End *********/

第五关:知识回顾 

  • 1、在多个线程访问同一个资源时,可以使用以下哪一项关键字实现线程同步( A

    A、synchronized
    B、static
    C、finally
    D、transient
  • 2、当线程调用start( )后,其所处状态为( D

    A、运行状态
    B、阻塞状态
    C、新建状态
    D、就绪状态
  • 3、下列关于Thread类提供的线程控制方法的说法中,错误的是( B

    A、线程A通过调用interrupt()方法来中断其阻塞状态
    B、若线程A调用方法isAlive()返回值为false,则说明A正在执行中,也可能是可运行状态
    C、currentThread()方法返回当前线程的引用
    D、线程A中执行线程B的join()方法,则线程A等待直到B执行完成

 

  • 47
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值