Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For this project, you will submit two .java files. You will need to run two clas

ID: 3821917 • Letter: F

Question

For this project, you will submit two .java files. You will need to run two classes simultaneously for this activity. Make sure you have a compiler that is capable of this.

For this project, you’re going to create a client-server connection using Java code that we’ve practiced in the Activities this semester. This program is a very simple server-based program that has many uses in the modern age, such as online banking, online gaming, school registries, and many more. For this project, we’re going to create an application for online shopping.

The idea here is simple. A user should be able to browse a small selection of fruits from an online vender, choose which one(s) to purchase and how many, and end the transaction.

This is how it’s going to work. A user will log on to the online store (which we will assume is done prior to the start of the application). For the purposes of this assignment, we’re going to use ‘localhost’ for the IP. You may use any PORT number you wish as long as it’s not reserved. When the application starts running, the user is logged in and given a list of fruits. The user may then select any of these options:

Display items chosen to buy

Purchase Bananas ($2 each)

Purchase Oranges ($3 each)

Purchase Pineapples ($5 each)

Purchase Watermelons ($8 each)

Finish Shopping

For the purposes of this assignment, we’re going to assume that the user has an unlimited amount of money for shopping purposes. The store, however, does not. When the server connects, the client will get the inventory from the store’s server so that the user will know how many of each item is in stock. When the user selects to purchase an item, the user will be prompted for the quantity to buy. Upon giving a quantity, the user’s cart should be updated with the number of the specific fruit and the client’s inventory should decrease by the amount purchased. Finally, when the user decides to finish shopping, the program should display the total cost of the items the user purchased and close the connection.

When your program starts, the server should accept a connection from the client, and then generate a random inventory of items. Each item should have a random stock assigned from 10 to 20. The inventory values should be sent to the client, which will then display them to the user within the menu of purchase options. When a purchase is made, the inventory should be updated in the client for the item purchased. The user’s current list of items should be stored on the client end and displayed neatly when the user chooses to see it. Finally, when the user is done shopping, the final list of items should be sent to the server, which will calculate the total price and update its own inventory, then send the total price to the client which will display the total and then finish execution.

There are a few guidelines that you must follow for this program. When you have finished creating the program, make sure to check back over these guidelines to make sure that everything has been accounted for.

The guidelines are as follows:

The program must be a console-based application. No GUIs allowed.

The program must loop through the options until the user selects to exit.

You may get user input any way you choose – however, you must catch invalid entries. This means that if your options are 1-6, then a user entry ‘F’ should be caught and give an invalid entry feedback, then allow the user to reenter their choice. Valid entries must also be checked when asking for quantities – positive integers only.

Your program must account for the amount of inventory in the store. If a user chooses to buy 10 pineapples and the store only has 8, then an error message should show and the purchase should not be completed.

User-friendliness is important! Make sure that your program looks nice and easy to use.

Send regular messages to the server’s console. At the very least, send a message when the server connects, when input is received from the client, and when the server disconnects.

Make sure that in the natural runtime of your program when the server is disconnected that all sockets, scanners, and any other form of I/O is closed – leaving these open can cause a security leak that, while harmless on a localhost, can be dangerous on other IPs.

Leave documentation and comments in your code to explain things step-by-step. This is just good practice. It doesn’t have to be a lot; just enough to explain your process in a simple way.

Code written must be your own. You are not allowed to copy code from any source, including but not limited to other students, textbooks, websites, etc.

Explanation / Answer

/************************************/
/*********** client.java ***********/
/***********************************/

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class Client
{

private static Socket socket;

public static void main(String args[])
{

Scanner sc = new Scanner(System.in);
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);

//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);

String message = "Connected to server";
bw.write(message);
bw.flush();

//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
  
int exit = 0;
while(exit != 5)
{
String message = br.readLine();
System.out.println(message); //Inventory and Stock message with options to buy


String number = sc.next();
bw.write(number);
bw.flush();

int temp = Integer.parseInt(number);
if(temp == 5)
{   
exit = 5;
message = br.readLine();
System.out.println(message);
System.out.println("GoodBye! Disconnected from server!");
break;
}

message = br.readLine(); //Quantity msg to buy or invalid number string
System.out.println(message);

if(message == "Please enter a valid number"){
continue;
}

number = sc.next();
bw.write(number);
bw.flush();

if(message == "Please enter valid quantity"){
continue;
}

  

}

}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}

/****************************************/
/**************server.java***************/
/****************************************/

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;


class Inventory{
   int bananas;
   int oranges;
   int pineapples;
   int watermelons;
   int totalPrice;

   Inventory(int bananas, int oranges, int pineapples, int watermelons){
       this.bananas = bananas;
       this.oranges = oranges;
       this.pineapples = pineapples;
       this.watermelons = watermelons;
   }

   public int getBananas(){
       return bananas;
   }

   public int getOranges(){
       return oranges;
   }

   public int getPineapples(){
       return pineapples;
   }

   public int getWatermelons(){
       return watermelons;
   }

   public void reduceBananas(int quantity){
       this.bananas -= quantity;
   }

   public void reduceOranges(int quantity){
       this.oranges -= quantity;
   }

   public void reducePineapples(int quantity){
       this.pineapples -= quantity;
   }

   public void reduceWatermelons(int quantity){
       this.watermelons -= quantity;
   }

   public void totalPrice(int quantity, int price){
       this.totalPrice += quantity * price;
   }

   public int getTotalPrice(){
       return this.totalPrice;
   }

}


public class Server
{

private static Socket socket;

public static void main(String[] args)
{

   Random r = new Random();
   int low = 10;
   int high = 20;
   int random1 = r.nextInt(high - low) + low;
   int random2 = r.nextInt(high - low) + low;
   int random3 = r.nextInt(high - low) + low;
   int random4 = r.nextInt(high - low) + low;

   Inventory inventory = new Inventory(random1, random2, random3, random4);

try
{

int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");

//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

//Recieve message from client
String welcomeMsg = br.readLine();
System.out.println(welcomeMsg);

//Present client with inventory
String message;
message = ":::Inventory:::";
message += "Bananas=" + inventory.getBananas() + ", Oranges=" + inventory.getOranges() + ", Pineapples=" + inventory.getPineapples + ", Watermelons=" + inventory.getWatermelons();
message += " 1. Purchase Bananas($2 each) 2. Purchase Oranges($3 each) 3. Purchase Pineapples($5 each) 4. Purchase Watermelons($8 each) 5. Finish Shopping";

//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(message);
bw.flush();

boolean notANumber=false;
String number = br.readLine();
try
{
int numberInIntFormat = Integer.parseInt(number);
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
notANumber = true;
}

if(notANumber)
{
   bw.write("Please enter a valid number");
   bw.flush();
}else{
   int typeOfFruit = Integer.parseInt(number);

   if(typeOfFruit == 5)
   {
       message = "Total Price for items is " + inventory.getTotalPrice();
       bw.write(message);
       bw.flush();
       break;
   }


   bw.write("Quantity?");
   bw.flush();

   number = br.readLine();
   try
   {
   int numberInIntFormat = Integer.parseInt(number);

   }
   catch(NumberFormatException e)
   {
   //Input was not a number. Sending proper message back to client.
   notANumber = true;
   bw.write("Please enter a valid number");
   bw.flush();
   }

   int quantity = Integer.parseInt(number);
   switch(typeOfFruit){
       case 1:
           if( quantity >=1 && quantity <= inventory.getBananas() )
           {
               inventory.reduceBananas(quantity);
               inventory.totalPrice(quantity, 2);
           }else{
               bw.write("Please enter valid quantity");
               bw.flush();
           }

       ;break;
       case 2:
           if( quantity >=1 && quantity <= inventory.getOranges() )
           {
               inventory.reduceOranges(quantity);
               inventory.totalPrice(quantity, 3);
           }else{
               bw.write("Please enter valid quantity");
               bw.flush();
           }

       ;break;
       case 3:
           if( quantity >=1 && quantity <= inventory.getPineapples() )
           {
               inventory.reducePineapples(quantity);
               inventory.totalPrice(quantity, 5);
           }else{
               bw.write("Please enter valid quantity");
               bw.flush();
           }
       ;break;
       case 4:
           if( quantity >=1 && quantity <= inventory.getWatermelons() )
           {
               inventory.reduceWatermelons(quantity);
               inventory.totalPrice(quantity, 8);
           }else{
               bw.write("Please enter valid quantity");
               bw.flush();
           }
       ;break;
   }

}

}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote