我是Java的新手,我坚持下面的任务。我被要求在AddressBook类中创建一个方法,该方法返回具有最高ActivityLevel总数的Person对象。
我创建了getSocialMediaActivityLevel(),maxValue()和findMostSocial()方法。
findMostSocial方法确实返回我所追求的值,但是赋值的描述包括语句:“要求您设计一个简单的算法并将其集成到现有的类中。”好像我已经使用了很多不必要的代码,但我不确定如何简化我所做的事情。任何帮助是极大的赞赏。
public class SocialMediaAccount {
private String userID;
private String websiteName;
private String websiteURL;
private int activityLevel;
public SocialMediaAccount(String userID, String websiteName, String websiteURL, int activityLevel) {
this.userID = userID;
this.websiteName = websiteName;
this.websiteURL = websiteURL;
this.activityLevel = activityLevel;
}
public void addSocialMediaAccount(String userID, String websiteName, String websiteURL, int activityLevel) {
SocialMediaAccount account1;
account1 = new SocialMediaAccount(userID, websiteName, websiteURL, activityLevel);
socialMediaAccounts.add(account1);
}
import java.util.ArrayList;
public class Person {
private String firstName;
private String surname;
private String mobile;
private String email;
private ArrayList<SocialMediaAccount> socialMediaAccounts;
//returns the combined ActivityLevel for all the Person's SocialMediaAccounts.
public int getSocialMediaActivityLevel(){
int total = 0;
for(SocialMediaAccount e : socialMediaAccounts){
total += e.getActivityLevel();
}
return total;
}
import java.util.ArrayList;
import java.util.Collections;
public class AddressBook {
private ArrayList<Person> contacts;
public AddressBook(){
contacts = new ArrayList<>();
}
//returns the highest combined ActivityLevel in the ArrayList contacts
public int maxValue(){
ArrayList<Integer> maxActivityLevel = new ArrayList<>();
for(Person e : contacts){
maxActivityLevel.add(e.getSocialMediaActivityLevel());
}
int maxValue = Collections.max(maxActivityLevel);
return maxValue;
}
//returns the Person object in the contacts ArrayList with the highest combined ActivityLevel
public Person findMostSocial(){
for(Person p: contacts){
if(maxValue() == p.getSocialMediaActivityLevel()){
return p;
}
}
return null;
}
答案 0 :(得分:0)
我认为这里需要的是Quick Sort算法,以确定人员列表中社交媒体活动的最大价值。所以,我建议用实现QuickSort的方法替换你的maxValue()和findMostSocial()方法。这是一个这样的implementation供参考。干杯