Writing Classes HW Post
Writing classes HW post for AP CSA
2021 FRQ 1a
public class WordMatch {
private String secret;
// Constructor for WordMatch that initializes the secret variable
public WordMatch(String word) {
secret = word;
}
// Method for comparing guess with secret
public int scoreGuess(String guess) {
int score = 0;
int occurrences = 0;
int guessLength = guess.length();
// The for loop's condition changes with respect to the length of guess, and counts the number of occurrences of guess in secret
for (int i = 0; i <= secret.length() - guessLength; i++) {
String secretComponent = secret.substring(i, i + guessLength);
if (guess.equals(secretComponent)) {
occurrences++;
}
}
score = occurrences * (int) Math.pow(guessLength, 2);
return score;
}
// Running method for visualizing outputs
public static void main(String[] args) {
WordMatch myObj = new WordMatch("mississippi");
System.out.println(myObj.scoreGuess("i"));
}
}
WordMatch.main(null);
2021 FRQ 3a
public class MemberInfo {
public String memberName;
public int memberGradYear;
public boolean memberGoodStanding;
// Constructor that initializes detail variables for a member
public MemberInfo(String name, int gradYear, boolean hasGoodStanding) {
memberName = name;
memberGradYear = gradYear;
memberGoodStanding = hasGoodStanding;
}
// Returns graduation year of a member
public int getGradYear() {
return memberGradYear;
}
// Returns the good standing status of a member
public boolean inGoodStanding() {
return memberGoodStanding;
}
}
public class ClubMembers {
// memberList ArrayList
private ArrayList<MemberInfo> memberList;
public void addMembers(String[] names, int gradYear) {
// memberList is initialized
memberList = new ArrayList<MemberInfo>();
// for loop adds all specified new member objects to MemberList
for (int i = 0; i < names.length; i++) {
// Alternate method: Create a memberInfo object first then append it to memberList
// MemberInfo memberObject = new MemberInfo(names[i], gradYear, true);
memberList.add(new MemberInfo(names[i], gradYear, true));
}
}
// Running method for visualizing outputs
public static void main(String[] args) {
ClubMembers myObj = new ClubMembers();
String[] names = {"Dylan", "Ritvik", "Aryan"};
myObj.addMembers(names, 2023);
// for loop retrieves all member objects from MemberList, then retrieves memberName, memberGradYear, and memberGoodStanding from each member object and prints them
for (int i = 0; i < myObj.memberList.size(); i++) {
String memberNameRetrieve = myObj.memberList.get(i).memberName;
int memberGradYearRetrieve = myObj.memberList.get(i).memberGradYear;
boolean memberGoodStanding = myObj.memberList.get(i).memberGoodStanding;
System.out.println(memberNameRetrieve + "; " + memberGradYearRetrieve + "; " + memberGoodStanding);
}
}
}
ClubMembers.main(null);