日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

类与类集合的基本使用

發布時間:2024/4/14 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 类与类集合的基本使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

設計人員類(姓名,性別,年齡,出生年月日),創建20位人員,年齡在(集合)(20-25)且隨機產生 存放在集合中,最后將年齡>24的人員刪除.
思路:定義類 Person 四個屬性 創建一個List集合對象
使用for循環來創建20位人員,隨機產生相關的屬性值
再使用for循環,過濾大于24歲的人員
通過增強for循環顯示滿足條件的人員信息

完成 person類+personMain類

package bean;

import java.util.Date;

public class Person {
private String name;
private String sex;
private int age;
private Date date;//日期

public Person(String name, String sex, int age, Date date) {
this.name = name;
this.sex = sex;
this.age = age;
this.date = date;
}
public Person(){}
public void setName(String name) {
this.name = name;
}

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

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

public void setDate(Date date) {
this.date = date;
}

public String getName() {
return name;
}

public String getSex() {
return sex;
}

public int getAge() {
return age;
}

public Date getDate() {
return date;
}
}

personMian.java

package com.company;

import bean.Person;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
* Created by lxj-pc on 2017/6/25.
*/
public class PersonMain {
public static void main(String[] args) {
//alt+enter 導入類所在位置 ArayList
//<>泛型聲明的類型 元素類型
List<Person> persons=new ArrayList<>();
Person person=null;


SimpleDateFormat sdf=
new SimpleDateFormat("yyyy-MM-dd");

for (int i=0;i<20;i++){
person=new Person();
person.setName("person-"+i);

person.setAge((int) (Math.random()*6+20));
//三元操作符號
person.setSex(Math.random()>0.5?"男":"女");

//2004-00-10
//拋出異常 捕獲異常
//異常的分類:
// 受控異常: 可以捕獲(try-catch)
// 非受控異常:程序運行時發生的異常,如索引越界,除數為0等(bug)
//年份:[1993,2005]
// 月份[1-12]
// 日:[1,30]
try {
int maxYear=2005;
int minYear=1993;
int year= (int) (Math.random()*(maxYear-minYear+1)+minYear);

//數據型d,字符類型s,%f 小數類型
//String.format("%d-%s-%s")
int month= (int) (Math.random()*12+1);
String monthStr =month<10?"0"+month:""+month;

person.setDate(sdf.parse(
String.format("%d-%s-10",year,monthStr )));
} catch (ParseException e) {
e.printStackTrace();
}

//添加到集合里去
persons.add(person);


}
//1-新元素 2-在哪取
System.out.println("處理前");
for (Person p:persons
) {
System.out.println(p.getName()+","+p.getAge()+","+sdf.format(p.getDate()));//日期轉成字符串

}
System.out.println("處理中");

//輸出集合中年齡超過24周歲
//對list集合元素刪除是 建議使用倒序方式
for (int i=persons.size()-1;i>=0;i--){
//如果方法有返回值 可以在方法后面添加
//.var 生成這個返回值的引用[局部變量]
//.field 生成這個返回值的引用[類成員變量]
if (persons.get(i).getAge()>=24){
persons.remove(i);
}
}
System.out.println("處理后");
for (Person p:persons
) {
System.out.println(p.getName()+","+p.getAge()+","+sdf.format(p.getDate()));//日期轉成字符串

}

}


}

轉載于:https://www.cnblogs.com/lxj666/p/7077561.html

超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生

總結

以上是生活随笔為你收集整理的类与类集合的基本使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。