求大神帮忙,这道题的Java代码

如题所述


import java.util.ArrayList;
import java.util.List;
import java.util.Random;

class Student {

public String name;
public int age;

public Student() {

}

public Student(String name, int age) {
this.age = age;
this.name = name;
}

public String toString() {
return "\nName: " + name + "  Age: " + age;
}

}
/**
 * 2015年9月8日下午11:22:51
 * @author cs12110 TODO 测试添加学生
 */
public class AddStudent {
/**
 * 产生[minNum,maxNum]之间的随机整数
 * 
 * @param minNum
 *            最小值
 * @param maxNum
 *            最大值
 * @return 返回整数
 */
public static int getRandomNum(int minNum, int maxNum) {
Random random = new Random();
int tempNum = random.nextInt(maxNum - minNum + 1) + minNum;
return tempNum;
}

/**
 * 产生随机名字
 * 
 * @param nameLen
 *            姓名长度
 * @return 名字字符串
 */
public static String getRandomName(int nameLen) {
String name = "";
for (int index = 0; index < nameLen; index++) {
name += (char) ((int) getRandomNum(97, 122));// 随即获取小写字母
}
return name;
}

/**
 * 检查stu是否存在列表stus里面
 * 
 * @param stus
 *            列表
 * @param stu
 *            学生对象
 * @return
 */
public static boolean isSame(List<Student> stus, Student stu) {
for (int index = 0; null != stus && index < stus.size(); index++) {
if (stu.name == stus.get(index).name
&& stu.age == stus.get(index).age)
return true;
}
return false;
}

/**
 * 初始化十名学生
 * 
 * @param list
 *            学生列表
 */
public static void init(List<Student> list) {
while (null != list && list.size() < 10) {
int age = getRandomNum(18, 50);// 获取随机年龄
int nameLen = getRandomNum(4, 7);// 获取名字长度
Student stu = new Student(getRandomName(nameLen), age);
if (!isSame(list, stu)) {// 列表不存在stu对象则添加
list.add(stu);
}
}
}

/**
 * 遍历学生列表
 * 
 * @param list
 *            学生列表
 */
public static void dispaly(List<Student> list) {
for (int index = 0; null != list && index < list.size(); index++) {
System.out.println(list.get(index));
}
}

public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
init(list);
dispaly(list);

}

}
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答