标签:
必做:1,2,3和4中的1)
选做:4中的2)和3)
1、请运行下面code,指出其功能;
(需附运行结果截图,并用简短文字描述其功能)
2、请将该code进行代码重构,使之模块化,并易于阅读和维护;
Driver.java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Driver {
private static String[] lastNames = {"Doe", "Smith", "Jones", "Adams", "Marshall", "Thompson", "Bradley", "Brown", "White", "Franklin", "Davis", "Cohn", "Clark"};
private static String[] firstNames = {"Mary", "John", "Susan", "Michael", "David", "Lisa", "Wendy", "Diane", "Kelly", "Claire", "Elizabeth", "Mitchell", "Richard"};
public static void main(String[] args) {
// create an empty list
List<Student> studentList = new ArrayList<>();
// initialize random generator
Random random = new Random();
// create random number of students
for (int i=0; i < 3; i++) {
// get random first name
String tempFirstName = firstNames[random.nextInt(firstNames.length)];
// get random last name
String tempLastName = lastNames[random.nextInt(lastNames.length)];
// get random age
int age = 18 + random.nextInt(20);
// create student
Student tempStudent = new Student(tempLastName, tempFirstName, age);
// add them to the list
studentList.add(tempStudent);
}
//print out the students
for (Student temp : studentList) {
System.out.println(temp);
}
}
}
Student.java
public class Student {
private String lastName;
private String firstName;
private int age;
public Student(String lastName, String firstName, int age) {
this.lastName = lastName;
this.firstName = firstName;
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return lastName + ", " + firstName + ", " + age;
}
}
小提示: 请模仿课堂上的示例,可采用手动重构,或使用eclipse提供的重构工具进行,
4、学习在项目中使用 jar 文件:
1 package mine;
2
3 import org.apache.commons.lang3.time.StopWatch;
4
5 public class Driver {
6
7 public static void main(String[] args) {
8 // TODO Auto-generated method stub
9 System.out.println("Running...");
10
11 StopWatch myStopWatch = new StopWatch();
12
13 myStopWatch.start();
14
15 performLengthyProcess();
16
17 myStopWatch.stop();
18
19 System.out.println("Time is:" + myStopWatch.getTime() + " millis");
20
21 System.out.println("Finished...");
22
23 }
24
25 private static void performLengthyProcess(){
26 try{
27 Thread.sleep(3000); //3 second delay
28
29 }catch(InterruptedException e) {
30 e.printStackTrace();
31 }
32 }
33
34 }
标签:
原文地址:http://www.cnblogs.com/xiaojun1009/p/4523259.html