【发布时间】:2021-05-03 19:51:03
【问题描述】:
我的任务有问题。我必须在 map
类动物
package com.company;
public class Animal {
public double body_wt;
public double brain_wt;
public double non_dreaming;
public double dreaming;
public double total_sleep;
public double life_span;
public double gestation;
public int predation;
public int exposure;
public int danger;
//getters and setters
@Override
public String toString()
{
return "AnimalCharacteristics{bodyWt="+getValue(body_wt)+", brainWt="+getValue(brain_wt)+", nonDreaming=" +
getValue(non_dreaming)+ ", dreaming="+ getValue(dreaming)+ ", totalSleep="+getValue(total_sleep)+
", lifeSpan="+getValue(life_span)+", gestation="+ getValue(gestation)+", predation="+predation+", exposure="+exposure+", danger="+danger+"}";
}
}
我从 txt 文件中读取动物
public static Map<String, Animal> readAnimals(){
Map<String, Animal> animals = new HashMap <>();
Scanner devScanner = null;
try {
devScanner = new Scanner(new File("mammals.txt"));
String species = "q";
devScanner.nextLine();
while (devScanner.hasNext()) {
Animal animal = new Animal();
String nextLine = devScanner.nextLine();
String[] anData = nextLine.split(";");
for (int i = 0; i < anData.length; i++) {
if (anData[i].isEmpty()) continue;
switch(i){
case 0: species = anData[0];continue;
case 1: if(anData[1].equals("NA")){animal.setBody_wt(0);} else{ animal.setBody_wt(Double.parseDouble(anData[1]));} continue;
case 2: if(anData[2].equals("NA")){animal.setBrain_wt(0);} else{ animal.setBrain_wt(Double.parseDouble(anData[2]));} continue;
case 3: if(anData[3].equals("NA")){animal.setNon_dreaming(0);} else{ animal.setNon_dreaming(Double.parseDouble(anData[3]));} continue;
case 4: if(anData[4].equals("NA")){animal.setDreaming(0);} else{ animal.setDreaming(Double.parseDouble(anData[4]));} continue;
case 5: if(anData[5].equals("NA")){animal.setTotal_sleep(0);} else{ animal.setTotal_sleep(Double.parseDouble(anData[5]));} continue;
case 6: if(anData[6].equals("NA")){animal.setLife_span(0);} else{ animal.setLife_span(Double.parseDouble(anData[6]));} continue;
case 7: if(anData[7].equals("NA")){animal.setGestation(0);} else{ animal.setGestation(Double.parseDouble(anData[7]));} continue;
case 8: if(anData[8].equals("NA")){animal.setPredation(0);} else { animal.setPredation(Integer.parseInt(anData[8]));} continue;
case 9: if(anData[9].equals("NA")){animal.setExposure(0);} else { animal.setExposure(Integer.parseInt(anData[9]));} continue;
case 10: if(anData[10].equals("NA")){animal.setDanger(0);} else { animal.setDanger(Integer.parseInt(anData[10]));} break;
}
}
animals.put(species, animal);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return animals;
}
【问题讨论】:
-
animalMap.values().stream().max(Comparator.comparingInt(Animal::getWeight))怎么样。 -
@sprinter 谢谢
标签: java dictionary