Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: I dont know why i cant save objects on my object list inside my server class

  1. #1
    Junior Member
    Join Date
    Apr 2024
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default I dont know why i cant save objects on my object list inside my server class

    okay so this is my server class
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.List;
     
    public class Server {
        private ServerSocket server;
        private static List<Accomodation> allAccommodations = new ArrayList<>();
     
        public static void main(String[] args) {
            new Server().openServer();
        }
     
        public synchronized static void addAccommodationToServer(Accomodation newAccommodation) {
            allAccommodations.add(newAccommodation);
        }
     
        public static List<Accomodation> getAllAccommodations() {
            return allAccommodations;
        }
     
        void openServer() {
            try {
                server = new ServerSocket(1234);
     
                while (true) {
                    Socket providerSocket = server.accept();
                    Thread t = new ActionsForClients(providerSocket, null);
                    t.start();
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }


    this is my client class



    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
     
     
    public class Client extends Thread 
    {
        private ObjectInputStream in;
        private ObjectOutputStream out;
        private  Scanner scanner;
        private static List<Accomodation> accomodations;
     
        public Client() 
        {
            scanner = new Scanner(System.in);
            accomodations = new ArrayList<>();
        }
     
        public void run() 
        {
            try (Socket requestSocket = new Socket("localhost", 1234)) {
                out = new ObjectOutputStream(requestSocket.getOutputStream());
                in = new ObjectInputStream(requestSocket.getInputStream());
     
                while (true) {
                    displayMenu();
                    int choice = readChoice();
                    processChoice(choice);
                    if (choice == 4) {
                        System.out.println("Exiting program...");
                        break;
                    }
                }
            } catch (UnknownHostException unknownHost) {
                System.err.println("You are trying to connect to an unknown host!");
            } catch (IOException ioException) {
                System.err.println("Error communicating with server: " + ioException.getMessage());
                ioException.printStackTrace();
            } finally {
                closeStreams();
            }
        }
     
        public synchronized static List<Accomodation> getAccomodations() {
            return accomodations;
        }
     
        private void displayMenu() 
        {
            System.out.println("Welcome back Manager.");
            System.out.println("What would you like to do?");
            System.out.println("Press 1 to add a new Accommodation.");
            System.out.println("Press 2 to add new dates for an existing accommodation.");
            System.out.println("Press 3 to see reservations for all accommodations.");
            System.out.println("Press 4 to exit the menu.");
            System.out.println("Enter a number:");
        }
     
        private int readChoice() {
            while (!scanner.hasNextLine()) {
                try {
                    Thread.sleep(100); // Sleep briefly to avoid busy-waiting
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                return Integer.parseInt(scanner.nextLine().trim());
            } catch (NoSuchElementException | NumberFormatException e) {
                System.err.println("Invalid input. Please enter a number.");
                return -1;
            }
        }
     
     
        private synchronized void addAccommodation() 
        {
            try (Scanner scanner = new Scanner(System.in)) 
            {
                System.out.println("Enter Room name:");
                String roomName = scanner.nextLine();
                System.out.println("Enter Number of persons:");
                int noOfPersons = Integer.parseInt(scanner.nextLine());
                System.out.println("Enter Area:");
                String area = scanner.nextLine();
                System.out.println("Enter Stars:");
                int stars = Integer.parseInt(scanner.nextLine());
                System.out.println("Enter Number of reviews:");
                int noOfReviews = Integer.parseInt(scanner.nextLine());
     
                Accomodation newAccommodation = new Accomodation(roomName, noOfPersons, area, stars, noOfReviews, null, null);
                accomodations.add(newAccommodation);
                System.out.println("Accommodation added to your accommodation list successfully.");
     
                Server.addAccommodationToServer(newAccommodation);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
     
     
     
     
        private void addAvailableDates() 
        {
            if (accomodations.isEmpty()) 
            {
                System.out.println("You have no accommodations in your list.");
            } else 
            {
                System.out.println("\nYour Accommodation List:");
                for (int i = 0; i < accomodations.size(); i++) 
                {
                    System.out.println((i + 1) + ". " + accomodations.get(i).getRoomName());
                }
                System.out.println("Choose the accommodation that you want to add new available dates to");
                try (Scanner scanner = new Scanner(System.in)) 
                {
                    int choiceacc=scanner.nextInt();
                    System.out.println("You chose "+accomodations.get(choiceacc).getRoomName()+"\nHow many dates do you want to add?");
                    int datescounter=scanner.nextInt();
                    for (int i = 0; i < datescounter; i++) 
                    {
                        System.out.println("Type the date you want to add:");
                        String newDate = scanner.nextLine();
                        accomodations.get(choiceacc).addAvailableDate(newDate);
                    }
                }
            }
        }
     
        private void SeeReservations() 
        {
            for (Accomodation accomodation : accomodations) 
            {
                System.out.println("Room: " + accomodation.getRoomName());
                System.out.println("Taken Dates:");
                if (accomodation.TakenDates != null) 
                {
                    for (String date : accomodation.TakenDates) 
                    {
                        System.out.println(date);
                    }
                } else 
                {
                    System.out.println("No reservations for this room.");
                }
                System.out.println("Available Dates:");
                if (accomodation.AvailableDates != null) 
                {
                    for (String date : accomodation.AvailableDates) 
                    {
                        System.out.println(date);
                    }
                } else 
                {
                    System.out.println("All dates are reserved for this room.");
                }
                System.out.println("--------------------------------");
            }
        }
     
     
     
        private void processChoice(int choice) 
        {
            switch (choice) 
            {
            case 1:
                System.out.println("You pressed 1");
                addAccommodation();
                break;
            case 2:
                System.out.println("You pressed 2");
                addAvailableDates();
                break;
            case 3:
                System.out.println("You pressed 3");
                SeeReservations();
                break;
            case 4:
                break;
            default:
                System.out.println("Invalid choice. Please enter a number between 1 and 4.");
            }
        }
     
     
        private void closeStreams() 
        {
            try 
            {
                if (in != null) in.close();
                if (out != null) out.close();
                scanner.close();
            } catch (IOException e) 
            {
                System.err.println("Error closing streams: " + e.getMessage());
            }
        }
     
        public static void main(String[] args) 
        {
            new Client().start();
        }
    }
    and this is my client user class
    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
     
    public class ClientUser extends Thread {
        private ObjectOutputStream out;
        private ObjectInputStream in;
        private Scanner scanner;
     
        public ClientUser() {
            scanner = new Scanner(System.in);
        }
     
        public void run() {
            try (Socket requestSocket = new Socket("localhost", 1234)) {
                out = new ObjectOutputStream(requestSocket.getOutputStream());
                in = new ObjectInputStream(requestSocket.getInputStream());
     
                while (true) {
                    displayMenu();
                    int choice = readChoice();
                    processChoice(choice);
                    if (choice == 4) {
                        System.out.println("Exiting program...");
                        break;
                    }
                }
            } catch (UnknownHostException unknownHost) {
                System.err.println("You are trying to connect to an unknown host!");
            } catch (IOException ioException) {
                System.err.println("Error communicating with server: " + ioException.getMessage());
                ioException.printStackTrace();
            } finally {
                closeStreams();
            }
        }
     
        private void displayMenu() {
            System.out.println("Welcome back Manager.");
            System.out.println("What would you like to do?");
            System.out.println("Press 1 to search for an accommodation.");
            System.out.println("Press 2 to make a reservation.");
            System.out.println("Press 3 to review an accommodation.");
            System.out.println("Press 4 to exit the menu.");
            System.out.println("Enter a number:");
        }
     
        private int readChoice() {
            try {
                return Integer.parseInt(scanner.nextLine().trim());
            } catch (NumberFormatException e) {
                System.err.println("Invalid input. Please enter a number.");
                return -1;
            }
        }
     
        private void processChoice(int choice) {
            switch (choice) {
                case 1:
                    System.out.println("You pressed 1");
                    List<Accomodation> testingloco = new ArrayList<>();
                    testingloco=Server.getAllAccommodations();
                    if(testingloco!=null)
                    {
                        System.out.println("NOT CRINGE");
                        for (Accomodation testingloc:testingloco)
                        {
                            System.out.println(testingloc.getRoomName());
                        }
                    }
                    else
                    {
                        System.out.println("CRINGE");
                    }
                    break;
                case 2:
                    System.out.println("You pressed 2");
                    // Handle making a reservation
                    break;
                case 3:
                    System.out.println("You pressed 3");
                    // Handle reviewing an accommodation
                    break;
                case 4:
                    break;
                default:
                    System.out.println("Invalid choice. Please enter a number between 1 and 4.");
            }
        }
     
        private void closeStreams() {
            try {
                if (in != null) in.close();
                if (out != null) out.close();
                scanner.close();
            } catch (IOException e) {
                System.err.println("Error closing streams: " + e.getMessage());
            }
        }
     
        public static void main(String[] args) {
            new ClientUser().start();
        }
    }
    I know my code is bad and sloppy but i'm new to this and its my first time trying anything with a server so please don't be disrespectful.
    Okay so the problem i am facing is that when i run my server and connect from the client class i can add a new accommodation to his personal list but when i try to add it to the server's list of all the accommodation nothing happens im in the process of trying to add some options to the clientuser's menu like filtering all of the accommondations by certain criteria but i can't do it if this doesn't work.
    If anyone takes the time to see this code and help me a bit that would be awesome.
    Last edited by stathis61; April 16th, 2024 at 03:45 PM.

  2. #2
    Member
    Join Date
    Jan 2024
    Posts
    43
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: I dont know why i cant save objects on my object list inside my server class

    It seems like you're experiencing an issue where the accommodations added from the client side are not being reflected in the server's list of all accommodations. Let's analyze your code and identify the potential problem.

    Looking at your `addAccommodation()` method in the `Client` class, you're correctly adding the new accommodation to the `accommodations` list maintained by the client. However, when you call `Server.addAccommodationToServer(newAccommodation) ;`, you're attempting to add the accommodation to the server's list using a static method `addAccommodationToServer` in the `Server` class.

    Here's where the issue might be:

    1. Your `addAccommodationToServer()` method is `static`, meaning it belongs to the class itself, not to any specific instance of the class. Static methods can't access instance variables directly. Thus, your `allAccommodations` list in the `Server` class might not be updated properly.

    2. In a multi-threaded environment like this, using `static` variables can lead to synchronization issues.

    To resolve this, you can try the following steps:

    1. Remove the `static` keyword from the `addAccommodationToServer()` method in the `Server` class. This way, it becomes an instance method and can access instance variables.

    2. Modify the `Client` class to maintain a reference to the `Server` instance, and use that reference to add accommodations to the server's list.

    Here's how you can do it:

    In the `Server` class:
    ```java
    public void addAccommodationToServer(Accomodation newAccommodation) {
    allAccommodations.add(newAccommodation);
    }
    ```

    In the `Client` class:
    ```java
    private Server server;

    public Client(Server server) {
    this.server = server;
    scanner = new Scanner(System.in);
    accomodations = new ArrayList<>();
    }

    // Inside addAccommodation() method
    public synchronized void addAccommodation() {
    // Your existing code
    server.addAccommodationToServer(newAccommodation);
    }
    ```

    And when creating instances of `Client` and `Server`, pass the `Server` instance to the `Client` constructor.

    With these changes, accommodations added by the client should be properly reflected in the server's list. If you encounter further challenges in your Java assignment, seeking guidance from online resources like ProgrammingHomeworkHelp.com that offer assistance with programming tasks could be beneficial.

Similar Threads

  1. Debugging with Print Statement (on List of Object Class)
    By siid14 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: June 19th, 2022, 03:44 AM
  2. [SOLVED] How to save/access class objects on a .txt file?
    By HyperRei in forum What's Wrong With My Code?
    Replies: 4
    Last Post: August 28th, 2021, 07:56 PM
  3. How to make an array list of objects in another object?
    By bonder in forum Collections and Generics
    Replies: 2
    Last Post: January 15th, 2019, 07:36 AM
  4. Replies: 5
    Last Post: March 2nd, 2012, 11:34 AM
  5. Replies: 2
    Last Post: November 5th, 2009, 10:15 PM