实验3 常用类(2学时)
**二、实验内容
1.在安排教师监考时,需要从一组教师中随机选取n个教师参加监考。要求实现一个类RandomTeacher的静态方法public static String[] getRandomTeachers(String[] teachers, int n),能够从teachers中随机选择n个教师(名字)并返回。
class RandomTeacher{
//使用HashSet,Rand来实现随机抽取功能
public static String[] getRandomTeachers(String[] teachers, int n){
Set<Integer> set = new HashSet<>();
while(set.size()<n)
{
int number = (int)(Math.random()*n);
set.add(number);
}
Iterator<Integer> it = set.iterator();
String[] nums = new String[n];
for(int i = 0;it.hasNext();i++)
{
nums[i] = teachers[it.next()];
}
return nums;
}
}
2.假设某餐馆中每桌顾客点菜记录的格式为“北京烤鸭:189 西芹百合:15 清蒸鲈鱼:80”(每道菜的价格与下一道菜的名字之间有一个空格)。编写一个类的方法,能够接受键盘录入的符合上述格式的点菜内容字符串,输出点菜记录中每种菜的价格及总价格。**
public class Main {
public static void main(String args[]) throws FileNotFoundException {
//使用map来存储数据,方便读入与取出
Map<String, Integer> dimp = new HashMap<>();
try {
//读取点菜的文件
File file1 = new File("C:\\Users\\fhawk\\IdeaProjects\\Test1\\src\\PTA\\dishes.txt");
BufferedReader r1 = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
String s = r1.readLine();
while (s != null) {
//将点菜文件以特定格式进行读取
String[] t = s.split(":");
if (t.length == 2) {
dimp.put(t[0], Integer.parseInt(t[1]));
}
// System.out.println(s);
s = r1.readLine();
}
r1.close();
} catch (Exception e) {
System.out.println(e);
}
int all = 0;
try {
//读取菜单文件
File file2 = new File("C:\\Users\\fhawk\\IdeaProjects\\Test1\\src\\PTA\\orders.txt");
InputStreamReader Re = new InputStreamReader(new FileInputStream(file2));
BufferedReader or = new BufferedReader(Re);
String s = or.readLine();
while (s != null) {
//将菜单的数据以特定格式分开进行读取
String[] t1 = s.split(",");
for (int i = 0; i < t1.length; i++) {
String t2[] = t1[i].split(":");
if (t2[0] != null)
all += dimp.get(t2[0]) * Integer.parseInt(t2[1]);
}
s = or.readLine();
}
or.close();
} catch (Exception e) {
System.out.println("路径2错误!");
}
System.out.println("总价格:" + all);
}
}