1、将字符串「a-b-c-d-e-f」按 「-」 切割,找到 「c」字符,替换为大写,然后倒序输出 「f-e-d-C-b-a」。
public class Test1 {
public static void main(String[] args) {
String s1 = "a-b-c-d-e-f";
String[] s2 = s1.split("-");
for(String s3:s2) {
System.out.println(s3);
}
String s4 = "";
for(int i = 0;i<s2.length;i++) {
s4 += s2[i] +"-";
}
String s5 = s4.substring(0,s4.length()-1);
s5 = s5.replace("c", "C");
System.out.println(new StringBuffer(s5).reverse().toString());
}
}
2、定义学生类(包含学号、姓名、年龄),将你所在小组组员添加到一个集合中,并按学号排序后输出。
public class Student implements Comparable<Student>{
private int code;
private String name;
private int age;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
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 Student(int code, String name, int age) {
super();
this.code = code;
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
int flag;
if (this.code > o.code) {
flag = -1;
} else if (this.code == o.code) {
flag = 0;
} else {
flag = 1;
}
return flag;
}
@Override
public String toString() {
return "Student [code=" + code + ", name=" + name + ", age=" + age
+ "]";
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
List<Student> teams = new ArrayList<Student>();
// 新建学生对象
Student stu1 = new Student(1, "陆洋", 24);
Student stu2 = new Student(3, "顾锐", 19);
Student stu3 = new Student(2, "关凌", 24);
Student stu4 = new Student(4, "钱佳雷", 25);
// 向集合添加学生对象
teams.add(stu1);
teams.add(stu2);
teams.add(stu3);
teams.add(stu4);
// 按学号倒叙排列
Collections.sort(teams);
// 遍历学生
for (Student stu : teams) {
System.out.println(stu);
}
}
}
3、紧接第二题,用单例设计一个服务类,并定义一个方法,可以随机抽取集合中的某个学生对象,并打印输出。import java.util.List;
public class Service {
private static Service service = new Service();
private Service() {
}
public static Service getInstance() {
return service;
}
public Student randomStu(List<Student> stus) {
if (null != stus && !stus.isEmpty()) {
return stus.get((int)(Math.random() * stus.size()));
} else {
return null;
}
}
}
import java.util.ArrayList;
import java.util.List;
public class Test3 {
public static void main(String[] args) {
List<Student> teams = new ArrayList<Student>();
Student stu1 = new Student(1, "陆洋", 24);
Student stu2 = new Student(3, "顾锐", 19);
Student stu3 = new Student(2, "关凌", 24);
Student stu4 = new Student(4, "钱佳雷", 25);
teams.add(stu1);
teams.add(stu2);
teams.add(stu3);
teams.add(stu4);
// 通过静态方法获取对象
Service service = Service.getInstance();
System.out.println("==========随机抽取学生=============");
Student randomStu = service.randomStu(teams);
System.out.println(randomStu);
}
}