Java 程序示例:实现了一个简单的社交媒体平台:

2023-10-16 09:00:07 浏览数 (3)

Java 程序示例:实现了一个简单的社交媒体平台:

代码语言:javascript复制
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class User {
    private String username;
    private String password;
    private List<Post> posts;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
        posts = new ArrayList<>();
    }

    public String getUsername() {
        return username;
    }

    public void addPost(Post post) {
        posts.add(post);
    }

    public List<Post> getPosts() {
        return posts;
    }
}

class Post {
    private String content;
    private String author;
    private List<String> comments;

    public Post(String content, String author) {
        this.content = content;
        this.author = author;
        comments = new ArrayList<>();
    }

    public String getContent() {
        return content;
    }

    public String getAuthor() {
        return author;
    }

    public void addComment(String comment) {
        comments.add(comment);
    }

    public List<String> getComments() {
        return comments;
    }
}

class SocialMediaPlatform {
    private Map<String, User> users;

    public SocialMediaPlatform() {
        users = new HashMap<>();
    }

    public void addUser(User user) {
        users.put(user.getUsername(), user);
    }

    public User getUser(String username) {
        return users.get(username);
    }
}

public class Main {
    public static void main(String[] args) {
        SocialMediaPlatform platform = new SocialMediaPlatform();

        User user1 = new User("alice", "password123");
        User user2 = new User("bob", "password456");

        platform.addUser(user1);
        platform.addUser(user2);

        Post post1 = new Post("Hello, world!", "alice");
        Post post2 = new Post("I love programming.", "bob");

        user1.addPost(post1);
        user2.addPost(post2);

        post1.addComment("Nice post!");
        post2.addComment("Keep up the good work!");

        System.out.println("User: "   user1.getUsername());
        System.out.println("Posts:");
        for (Post post : user1.getPosts()) {
            System.out.println("Content: "   post.getContent());
            System.out.println("Author: "   post.getAuthor());
            System.out.println("Comments:");
            for (String comment : post.getComments()) {
                System.out.println("- "   comment);
            }
            System.out.println("-----------------------");
        }
    }
}

这个程序示例实现了一个社交媒体平台,包括用户类 User,帖子类 Post 和社交媒体平台类 SocialMediaPlatform。用户类具有用户名、密码和帖子列表等属性,并提供添加帖子和获取帖子列表的方法。帖子类具有内容、作者和评论列表等属性,并提供添加评论和获取评论列表的方法。社交媒体平台类具有用户列表,并提供添加用户和获取用户的方法。

main 函数中,示例创建了一个社交媒体平台对象 platform,并在平台上添加了两个用户 user1user2,然后每个用户都发布了一个帖子,并给帖子添加了评论。最后,打印了用户1的帖子及其评论。

0 人点赞