Java_Optional_編程題

基於Optional操作

需求描述中的指定X,均指方法的參數

有返回值的方法,嘗試直接編寫return語句,基於Optional操作直接返回所需結果

嘗試使用簡寫

注意過濾代碼格式

基於給定課程,如果課程不是選修課,返回課程的名稱

任何不符合條件,返回 課程不存在

import java.util.Optional;
import java.util.Scanner;

public class Course {
	 private String name;
	 private boolean elective;
	 private Teacher teacher;
	 public Course(String name, boolean elective, Teacher teacher) {
		 this.name = name;
		 this.elective = elective;
		 this.teacher = teacher;
     }
	 public String getName() {
		 return name;
	 }
	 public void setName(String name) {
		 this.name = name;
	 }
	 public boolean isElective() {
		 return elective;
	 }
	 public void setElective(boolean elective) {
		 this.elective = elective;
	 }
	 public Teacher getTeacher() {
		 return teacher;
	 }
	 public void setTeacher(Teacher teacher) {
		 this.teacher = teacher;
	 }
}

class Teacher {
    private String name;
    public Teacher(String name) {
    	this.name = name;
    }
    public String getName() {
    	return name;
    }
    public void setName(String name) {
    	this.name = name;
    }
}

class Test {
	public static void main(String[] args) {  
		Teacher t1=new Teacher("sh");
		Course c1=new Course("數學",true,t1 );
		Teacher t2=new Teacher("shr");
		Course c2=new Course("語文",true,t2 );
		Teacher t3=new Teacher("gh");
		Course c3=new Course("java",false,t3);
		f(c3);f(c2); 
	}
	public static void f(Course c){
		//基於給定課程,如果課程不是選修課,返回課程的名稱
		//任何不符合條件,返回 課程不存在
		if(c!=null){
			if(c.isElective()==false){
				System.out.println(c.getName());
			}else
			{
				System.out.println("課程不存在");
			}
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章