I have written a program for a photo upload site where users can like photos, I have a test script to like the photo then display all the likes then i want to remove the like and display all the likes now. How do i do this?
import java.util.*;
public class Likes {
private static Hashtable<Photo, TreeSet<User>> likes = new Hashtable<>();
//like photo
public static void like(Photo photo, User user) {
try {
likes.get(photo).add(user);
}
catch (NullPointerException e) {
likes.put(photo, new TreeSet<>());
likes.get(photo).add(user);
}
}
//unlike photo
public static void unlike(Photo photo, User user) {
try {
likes.get(photo.remove(user));
}
catch (NullPointerException e) {
}
}
//has liked photo
public boolean hasliked(Photo photo, User user) {
try {
return likes.get(photo).contains(user);
}
catch (NullPointerException e) {
return false;
}
}
//get all likes
public List<Photo> getAllLikes(User user){
// new empty list
List<Photo> likedphotos = new ArrayList<Photo>();
for (Photo photo : likes.keySet()) {
if(hasliked(photo, user)){
// add photo to list
likedphotos.add(photo);
}
// return that initial list
}
return likedphotos;
}
public String toString() {
return likes.toString();
}
public void get(Photo remove) {
}
public void remove(Photo photo1, User user1) {
}
}
Tests:
import java.sql.SQLOutput;
import java.util.*;
public class TestDrive {
public static void main(String[] args) throws InputValidationException {
//create 2 photo object
Photo photo1 = new Photo();
Photo photo2 = new Photo();
//create 1 user object
User user1 = new User();
//create 1 like object
Likes likes1 = new Likes();
//set 2 photos
photo1.setimageURL("photo of user 2");
photo2.setimageURL("photo of user 1");
//print the 2 photos
System.out.println(photo1.getimageURL());
System.out.println(photo2.getimageURL());
//set 1 user
user1.setUserName("oopnoob");
//print the username
System.out.println(user1.getUserName());
//Like the 2 photos
Likes.like(photo1, user1);
Likes.like(photo2, user1);
//Test the hasliked method to see if user1 has liked both photos - both should return true
System.out.println("Should be true: " + likes1.hasliked(photo1, user1));
System.out.println("Should be true: " + likes1.hasliked(photo2, user1));
//Test the getAllLikes for user1. Should print 2 photos.
System.out.println("user1 liked: " + likes1.getAllLikes(user1));
//i dont know how to remove the like from the photo
//Test the unlike feature by unliking photo1
likes1.unlike(photo1, user1);
//Test the getAllLikes - should only print one photo
System.out.println("user1 liked: " + likes1.getAllLikes(user1));
}
}
Aucun commentaire:
Enregistrer un commentaire