Link to home
Start Free TrialLog in
Avatar of pimpp1184
pimpp1184

asked on

NIM game ... server/client program. Can't get it to work no matter what I do

I need to make a really simple game of Nim in which you connect to a server and play it  Not only is the game a Client-Server program, the server class implements runnable (so the game will accept new clients in the server) and the client is a thread as well. I have no idea what isn't workin at all. In the game the server part is supposed to ask the client how many sticks they want to play with, then it will ask how many sticks can we pick up per turn, who should go first (your or me) ... then the real part of the game will start (it will say you move first. how many sticks do you want to take?. And so on.

Here is the program:

/** SERVER **/
import java.io.*;
import java.util.*;
import java.net.*;

public class NimServer2 implements Runnable {

      final static int PORT = 10101;
      private ServerSocket nimListen;
      private int gameSticks, minSticks, maxSticks, sticksLeft, clientSticks, serverSticks;
      private BufferedReader fromClient;
      private PrintWriter toClient;
      private Random rand;
      private boolean gameStarted;
      private Buffer2 buff;

      public NimServer2(){

            buff = new Buffer2();
            rand = new Random();

            gameStarted = false;
            try {
                  nimListen = new ServerSocket(PORT);
            } catch (IOException e){}
            System.out.println("NimServer Started... Waiting for a player...");
      }

      public void run(){
            try {
                  while(true){
                        Socket player = nimListen.accept();
                        System.out.println("\nAccepted a connection from " +
                                    player.getInetAddress().toString());

                        InputStream in = player.getInputStream();
                        OutputStream out = player.getOutputStream();

                        fromClient = new BufferedReader(new InputStreamReader(in));
                        toClient = new PrintWriter(out, true);

                        if(!gameStarted){
                              startNewGame();
                              gameStarted = true;
                              toClient.println("MESSAGE FROM SERVER: Let's Play NIM. Whoever Picks up the last stick wings? \n"    + "How many sticks do you want to play with?";
                        } else {
                              serverMove();
                        }
                  }

            } catch(IOException ioe){
                  System.out.println("IO error... in Server");
            }
      }

      private void serverMove(){

            buff.serverMove();
            try {
                  clientSticks = Integer.parseInt(fromClient.readLine());
                  int tmpSticksLeft = sticksLeft - clientSticks;
                  serverSticks = 1 + rand.nextInt(maxSticks);
                  sticksLeft = tmpSticksLeft - serverSticks;
                  toClient.println("SERVER: That leaves " + tmpSticksLeft +
                              " sticks. I pick up " + serverSticks + ". " +
                              sticksLeft + " sticks remain.");
            } catch (NumberFormatException nfe){
            } catch (IOException ioe){}
      }

      private void startNewGame(){
            gameSticks = 31;
            minSticks = 1;
            maxSticks = 4;
            sticksLeft = 0;
            serverSticks = 0;
      }

      public static void main(String[] args){
            NimServer2 ns = new NimServer2();
            Thread nimServ = new Thread(ns);
            nimServ.start();
      }
}


/** CLIENT **/
import java.net.*;
import java.io.*;

public class NimClient implements Runnable {

      final static int PORT = 10101;
      private Socket nimSock;
      private BufferedReader fromServer, userIn;
      private PrintWriter toServer;
      private boolean isDone, gameStarted;
      private Thread nimPlayer;
      private int tempNum = 0;
      private Buffer2 buff;

      public NimClient(String serverIP){


            try{
                  nimSock = new Socket(serverIP, PORT);
                  System.out.println("CLIENT: connected to " + serverIP + ":" + PORT);

                  InputStream input = System.in;
                  InputStream in = nimSock.getInputStream();
                  OutputStream out = nimSock.getOutputStream();

                  userIn = new BufferedReader(new InputStreamReader(input));
                  fromServer = new BufferedReader(new InputStreamReader(in));
                  toServer = new PrintWriter(out, true);
            } catch (UnknownHostException uhe){
                  System.out.println("Cannot connect to host");
                  System.exit(0);
            } catch (IOException ioe){
                  System.out.println("IO error in Client");
                  System.exit(0);
            }

            buff = new Buffer2();
            isDone = false;
            gameStarted = false;

      }

      public void run() {
            while(!isDone){
                  try {
                        if (!gameStarted){
                              System.out.println(fromServer.readLine());
                              gameStarted = true;
                        } else {
                              buff.clientMove();
                              System.out.println(fromServer.readLine());
                              System.out.print("How many sticks do you take?\nINPUT: ");
                              tempNum = Integer.parseInt(userIn.readLine());
                              toServer.println(tempNum);
                        }
                  } catch(NumberFormatException nfe){
                  } catch(IOException ioe){}
            }
      }


      public static void main(String[] args){
            if(args.length != 1){
                  System.out.println("Usage: java NimClient \"HOST IP ADDRESS\"");
                  System.exit(0);
            } else {

                  NimClient nc = new NimClient(args[0]);

                  Thread nimPlayer = new Thread(nc);
                  nimPlayer.start();
            }
      }
}


Thank you for all your help.
Avatar of lwinkenb
lwinkenb

To start with, there is a design error in your server.  Right now, you have the Server running on its own thread, instead of having each connection run on a new thread.

The loop that looks like:
while(true){
                    Socket player = nimListen.accept();

Should not be in the run() method.  You could probably put that loop in the main method.  Then when a new client connects, you can start a new thread and pass that thread an instance of the socket (player in your example).  You might want to consider putting the connection in a new class (call it Connection for instance), and have that class be the one that extends Thread or implement Runnable.

Then you could do this:
while(true) {
Socket player = nimListen.accept();
Connection newConnection = new Connection(player);
newConnection.start();
someDataStructure.add(newConnection); // Have a data structure to hold all the started threads
}

The connection class would look something like:

class Connection extends Thread {
  Socket socket;
  BufferedReader socketIn;
  PrintWriter socketOut;

  public Connection(Socket socket) {
    this.socket = socket;
    //initialize the socketIn and socketOut variables
  }

  public void run() {
    //Start the game here
  }
}




Also you currently have your client running on a seperate thread.  This isnt neccessary, your client doesnt need it (unless you're planning on adding some additional functionality later on that will require it.  I dont know how the game Nim works to be honest).

As far as I can tell, the client just needs a big while loop:

while(true) {
//read input from the console
//then send data to the server
//then handle the server response
}

Now if the server needs to send data back to the client at random times (not just when the client is listening for a response), then you will need to run a seperate thread to listen for messages from the server.  This will depend on the complexity of the game though.
Avatar of pimpp1184

ASKER

Wow ... I think I am lost sorry. The way the game NIM works is as follows (as according to what the program is supposed to work like):
1) First the server will ask: How many sticks do you want to play with?
2) Then the client will reply back with a answer.
3) The server will then ask another question in which it will ask ... How many sticks can we pick per turn?
4) The client would reply back with an answer.
5) The server will then ask ... who should go first (YOU or ME)?
6) The client will reply back with an answer of a YOU or ME
7) The server will then confirm the rules. Ex: The rules are 31 sticks, 4 max sticks per movie. You firsy. Okay?
8) The client will then reply back with a Okay
9) The server will then ask .. Your move first. How many stick do you want to take?"
10) The client will then choose a number between 0 to 4.
11) The server will delete the clients number from the total number of sticks and the server will randomly choose a number between 0 to 4 and then tell how many sticks remain.
12) This will go on until there are no sticks remaining. Whoever picks the last number will win?

I hope this explained to how the game is supposed to work. Thanks
I totally forgot to add this other class I had for the code:

public class Buffer2 {
      
      private boolean available;      //which thread is available

      
      public Buffer2(){
            
            available = false;
      }
      
      public synchronized void serverMove(){
            while (!available){
                  try {
                        wait();
                  } catch (InterruptedException ie){}
            }
                  
            setAvailable(false);
            return;
      }
      
      
      public synchronized void clientMove(){
            
            while(available){
                  try {
                        wait();
                  } catch (InterruptedException ie){}
            }
            
            setAvailable(true);
            return;
      }

      private synchronized void setAvailable(boolean a) {
            boolean statusChange = (a != available);
            
            available = a;
            if(statusChange) {
                  notify();                        
            }      
      }
}

Thanks
Hmm... if you were lost from reading my comments, then you should probably read up on some tutorials on threads before you try doing this project.  

http://www.tipsmart.com/studytools/tutorials/threads.htm
http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.html

Hi. I am sorry. I understand the threads and all but I am still confused to how I am supposed to get the game to work and stuff. Sorry for being such an annoyance.
Hi. Alright I am starting form scratch again ... but I am gettin a error in one of my classes ... I am gonna post the code and say what problem it is giving me

import java.net.*;
import java.io.*;
import java.awt.*;

public class KnockKnockProtocol
{
    public String processInput(String theInput)
    {
        String theOutput = null;

              String line;
            System.out.println("Let's Play NIM. Whoever Picks the last stick wins. Let's \n"
                              + "decide the rules. How many sticks do you want ot play with?");

               try
               {
                 BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
                 line = in.readLine();
                 /*while ( line != null )  // continue until end of file
                 {
                   line = in.readLine();
                 }
                 in.close();*/
               }
               catch ( IOException iox )
               {
                 System.out.println("Problem reading "  );
                  }


             String line2;
                  System.out.println("How many sick can we pick per turn");
               try
               {
                       BufferedReader in2 = new BufferedReader( new InputStreamReader( System.in ) );
                       line2 = in2.readLine();
               }
               catch ( IOException iox )
               {
                       System.out.println("Problem reading "  );
               }

               String line3;
               System.out.println("Who should go first. (YOU or ME)");
               try
               {
                       BufferedReader in3 = new BufferedReader( new InputStreamReader( System.in ) );
                       line3 = in3.readLine();
               }
               catch ( IOException iox )
               {
                       System.out.println("Problem reading "  );
               }


               System.out.println("The rules are" + line + "sticks");

        return theOutput;
    }
}


It is giving me this error:
C:\Param's Stuff\Second Year at R.I.T\Computer Programming 3\crap\2\KnockKnockProtocol.java:56: variable line might not have been initialized
               System.out.println("The rules are" + line + "sticks");
                                                                                       ^
1 error

                                                                                       
The error is because you are initializing the variable line inside a try block.  If an exception is thrown, then line might not get initialized - that's why it is complaining.

You can fix this by chaning your variable declaration to:
String line = "";

That way it is initialized for sure.
Also, there is no reason to declare a new bufferedreader object every time you want to read from the console:

I suggest this instead:


import java.net.*;
import java.io.*;
import java.awt.*;

public class KnockKnockProtocol
{
    public String processInput(String theInput)
    {
            String theOutput = null;

            String strHowManySticks      = "";
            String strSticksPerTurn = "";
            String strFirstPlayer = "";
            System.out.println("Let's Play NIM. Whoever Picks the last stick wins. Let's \n"
                           + "decide the rules. How many sticks do you want ot play with?");

             try
             {
               BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) );
               strHowManySticks = stdin.readLine();
               
               System.out.println("How many sick can we pick per turn");
               
               strSticksPerTurn = stdin.readLine();
               
               System.out.println("Who should go first. (YOU or ME)");
               
               strFirstPlayer = stdin.readLine();
               
               System.out.println("The rules are" + line + "sticks");

             }
             catch ( IOException iox )
             {
               System.out.println("Problem reading "  );
             }
             
        return theOutput;
    }
}

Also notice how I made some better names for your String variables.  Calling them String1, String2, etc will just confuse you later on.  Make the variable names descriptive so that you know what they are used for.
I am so stupid ... thanks for the help. I appreciate it. I am gonna try some more of this and see if I get into more trouble hoepfully not this time. Thanks again.
no problem.  Hope all goes well.
oh here we go again ... I don't know what I am doing wrong. The code is fine .. it compiles and everything but it don't work. I am gonna post the codes that I have and then I will try to tell what problem I am experiencing now:

SERVER:
import java.net.*;
import java.io.*;

public class KnockKnockServer
{
    public static void main(String[] args) throws IOException
    {

        ServerSocket serverSocket = null;
        try
        {
            serverSocket = new ServerSocket(4444);
        }
        catch (IOException e)
        {
            System.err.println("Could not listen on port: 4444.");
            System.exit(1);
        }

        Socket clientSocket = null;
        try
        {
            clientSocket = serverSocket.accept();
        }
        catch (IOException e)
        {
            System.err.println("Accept failed.");
            System.exit(1);
        }

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(      new InputStreamReader(
                                          clientSocket.getInputStream()));
        String inputLine, outputLine;
        KnockKnockProtocol kkp = new KnockKnockProtocol();

        outputLine = kkp.processInput(null);
        out.println(outputLine);

        while ((inputLine = in.readLine()) != null)
        {
             outputLine = kkp.processInput(inputLine);
             out.println(outputLine);
             if (outputLine.equals("Bye."))
                break;
        }
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    }
}


CLIENT:
import java.io.*;
import java.net.*;

public class KnockKnockClient
{
    public static void main(String[] args) throws IOException
    {
        Socket kkSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try
        {
            kkSocket = new Socket("param", 4444);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
        }
        catch (UnknownHostException e)
        {
            System.err.println("Don't know about host: param.");
            System.exit(1);
        }
        catch (IOException e)
        {
            System.err.println("Couldn't get I/O for the connection to: param");
            System.exit(1);
        }

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromServer;
        String fromUser;

        while ((fromServer = in.readLine()) != null)
        {
            System.out.println("Server: " + fromServer);
            if (fromServer.equals("Bye."))
                break;

            fromUser = stdIn.readLine();
                if (fromUser != null)
                {
                System.out.println("Client: " + fromUser);
                out.println(fromUser);
                }
        }

        out.close();
        in.close();
        stdIn.close();
        kkSocket.close();
    }
}

The program that does all the calculations:
import java.net.*;
import java.util.Random;
import java.io.*;
import java.awt.*;

public class KnockKnockProtocol
{
    public String processInput(String theInput)
    {
            String theOutput = null;

            String strHowManySticks     = "";
            String strSticksPerTurn = "";
            String strFirstPlayer = "";
            String confirmOkay = "";
            String meString = "";
            String compString = "";
            System.out.println("Let's Play NIM. Whoever Picks the last stick wins. Let's \n"
                             + "decide the rules. How many sticks do you want ot play with?");

             try
             {
               BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) );
               strHowManySticks = stdin.readLine();

               System.out.println("How many sick can we pick per turn");

               strSticksPerTurn = stdin.readLine();

                     //while((strFirstPlayer != "YOU") || (strFirstPlayer != "ME"))
                     //{
               System.out.println("Who should go first. (YOU or ME)");

               strFirstPlayer = stdin.readLine();
               //}

               System.out.println("The rules are " + strHowManySticks + " sticks, " + strSticksPerTurn +
                                  " max sticks per move. You first. Okay?");

               confirmOkay = stdin.readLine();

               if (confirmOkay == "Okay")
               {
                           if(strFirstPlayer == "ME")
                           {
                                 System.out.println("Your move first. How many stick do you take");
                                 meString = stdin.readLine();

                                 int spt = Integer.parseInt(strSticksPerTurn);
                                 Random rnd = new Random();
                                 int a = rnd.nextInt(spt);

                                 int mhs = Integer.parseInt(strHowManySticks);
                                 int myStr = Integer.parseInt(meString);
                                 int b = (mhs - myStr);
                                 int c = (b - a);

                                 System.out.println("That leaves " +b+ " sticks. I pick up " +a+ ". " +c+ " sticks remain.");

                              }
                   }

             }
             catch ( IOException iox )
             {
               System.out.println("Problem reading "  );
             }



        return theOutput;
    }
}

The problem is that the IF statements in the program where it does all the calculations are not working fine. For example, the if statement which is if(confirmOkay == "Okay") { ... } .. none of the stuff in that statement works. I don't know waht is wrong with it. I hope you are able to find that problem. Thanks




you cant compare strings like that since they are objects and not pimitive data types.

The correct way to do it is:

if(confirmOkay.equals("Okay")) {...}
oh ok .. i knew i did that somewhere ... damnit sorry for being such an annoyance
no problem at all.
alright here I go again ... the part, this time, that I can't get to work is in this part of the code:
 if (confirmOkay.equals("Okay"))
               {
            if(strFirstPlayer.equals("ME"))
            {
               System.out.println("Your move first. How many stick do you take");
               meString = stdin.readLine();

               int spt = Integer.parseInt(strSticksPerTurn);
               Random rnd = new Random();
               int a = rnd.nextInt(spt);

               int mhs = Integer.parseInt(strHowManySticks);
               int myStr = Integer.parseInt(meString);
               int b = (mhs - myStr);
               int c = (b - a);

               System.out.println("That leaves " +b+ " sticks. I pick up " +a+ ". " +c+ " sticks remain.");

            }
      }

I gotta have a loop in this if-loop somewhere. What I have to do is I gotta keep subtracting the number of sticks everytime I choose how many sticks I want to take out and then the computer takes out until all the sticks are gone. Then the connection will close. I hope u understood this because I barely did ... thanks again man
like this maybe?
this is just a simple while loop that runs until there are no sticks left.

int mhs = Integer.parseInt(strHowManySticks);
while(mhs > 0) {
             System.out.println("Your move first. How many stick do you take");
             meString = stdin.readLine();

             int spt = Integer.parseInt(strSticksPerTurn);
             Random rnd = new Random();
             int a = rnd.nextInt(spt);

             mhs = Integer.parseInt(strHowManySticks);
             int myStr = Integer.parseInt(meString);
             mhs -= myStr; // mhs = mhs - myStr
             mhs -= a;

             System.out.println( I pick up " +a+ ". " +mhs+ " sticks remain.");
}
alright the loop works but how can i make it so that the number of sticks are decreased every time i choose a number of sticks to be taken and then the program will continue until all the sticks are finished with. I hope u got what I was sayin
For Example:
**you start with 31 sticks and you can only choose up to 4 sticks per turn**

Server: Your move first. How many sticks do u take?
Input: 1
Server: That leaves 30 sticks. I pick up 4. 26 sticks remain. How many sticks do u take?
Input: 1
Server: That leaves 25 sticks. I pick up 4. 21 sticks remain. How many sticks do u take?
Input: 1
Server: That leaves 20 sticks. I pick up 2. 18 sticks remain. How many sticks do u take?
Input: 3:
Server: That leaves 15 sticks. I pick up 4. 11 sticks remain. How many sticks do u take?
Input: 1
Server: That leaves 10 sticks. I pick up 3. 7 sticks remain. How many sticks do u take?
Input: 1
Server: That leaves 5 sticks. I pick up . 2 sticks remain. How many sticks do u take?
Input: 2
Server: You picked up the last stick. You win!
Client: connection closed

I think u would understand what I am sayin by this. Thanks for all your help
Can anyone help me with this? Sorry for being a pain. Thanks
int sticksLeft = //the number of sticks left

while(sticksLeft > 0) {
  //you pick up sticks.  subtract those from sticksLeft
  //server picks up sticks.  subtract those from sticksLeft
  //output the new number of sticks left
}
// print out who won.
More questions ... I can't get something to work again.
For example:
Server: Your move first. How many sticks do u take?
Input: 1
Server: That leaves 30 sticks. I pick up 4. 26 sticks remain. How many sticks do u take?
Input: 1
Server: That leaves 25 sticks. I pick up 4. 21 sticks remain. How many sticks do u take?
Input: 1

When it says "That leaves 30 sticks" and "That leaves 25 sticks" .. I can't get that part to work. This should show after the user types his input. I can't get the line that the server displays to show up on my program.
-----------------------------------------------------------------------------------------------------------------------------------------------------
My other question is what do I have to do to show who won the game.
for example:
Input: 1
Server: That leaves 5 sticks. I pick up . 2 sticks remain. How many sticks do u take?
Input: 2
Server: You picked up the last stick. You win!
Client: connection closed

Such as whoever picks the last stick the server will display who won. In this example, the user picks the last sticks and what if the computer picks the last sticks. I have no idea how to do this. I will keep on trying. Thanks again for all your help.
oh forgot to put the code in:
 if (confirmOkay.equals("Okay"))
               {
         if(strFirstPlayer.equals("ME"))
         {
                int mhs = Integer.parseInt(strHowManySticks);
               while(mhs > 0)
               {
                    System.out.println("Your move first. How many stick do you take");
                    meString = stdin.readLine();

                    int spt = Integer.parseInt(strSticksPerTurn);
                    Random rnd = new Random();
                    int a = rnd.nextInt(spt);

                    int myStr = Integer.parseInt(meString);
                              mhs -= myStr;
                    mhs -= a;
                    //mhs = mhs - myStr;
                    //int mhs2 = mhs - a;

                    System.out.println("That leaves " +mhs2+ " sticks. I pick up " +a+ ". " +mhs+ " sticks remain.");
            }
            //int result = mhs - a;
            //if()
                       //{
       }
      }
For your first question:

totalSticks = 31;
System.out.println("Your move first, how many do you pick up?");
int iTake = // user input
int compTake = // Random number for computer to take away
System.out.println("That leaves " + totalSticks-iTake + " sticks.  I pick up " + compTake + ".  " + (totalSticks-iTake-compTake) + " sticks remain.  How many sticks do you take?");
totalSticks = totalSticks - iTake - compTake;

For the second question:


System.out.println("Your move first, how many do you pick up?");
int iTake = // user input
if((totalSticks-iTake) == 0) {
  System.out.println("you have won the game");
  break;
}
int compTake = // Random number for computer to take away
if((totalSticks-iTake-compTake) <= 0) {
  System.out.println("I have won the game");
  break;
}

The break statement will take you outside the while loop.  
while() {
// all you code is in here
}
// now close the connection out here




Thanks for the quick reply. The first question I asked works fine but the second part doens't work like how I want it to. This is an example of the output of the game.


Let's Play NIM. Whoever Picks the last stick wins. Let's
decide the rules. How many sticks do you want ot play with?
30
How many sick can we pick per turn
5
Who should go first. (YOU or ME)
ME
The rules are 30 sticks, 5 max sticks per move. You first. Okay?
Okay
Your move first. How many stick do you take
5
That leaves 25 sticks. I pick up 3. 22 sticks remain.
Your move first. How many stick do you take
2
That leaves 20 sticks. I pick up 0. 20 sticks remain.
Your move first. How many stick do you take
5
That leaves 15 sticks. I pick up 3. 12 sticks remain.
Your move first. How many stick do you take
2
That leaves 10 sticks. I pick up 2. 8 sticks remain.
Your move first. How many stick do you take
5
That leaves 3 sticks. I pick up 0. 3 sticks remain.
I have won the game

As you can see that the computer automatically wins even when there are 3 sticks remaining. I have no idea what is wrong with this.
The code:
if (confirmOkay.equals("Okay"))
{
        if(strFirstPlayer.equals("ME"))
        {
        int mhs = Integer.parseInt(strHowManySticks);
        while(mhs > 0)
        {
              System.out.println("Your move first. How many stick do you take");
              meString = stdin.readLine();
              int myStr = Integer.parseInt(meString);

              int spt = Integer.parseInt(strSticksPerTurn);
              Random rnd = new Random();
              int a = rnd.nextInt(spt);

              System.out.println("That leaves " +(mhs-myStr)+ " sticks. I pick up " +a+ ". " +(mhs-myStr-a)+ " sticks remain.");
              mhs = mhs-myStr-a;

                        if((mhs-myStr) == 0)
              {
            System.out.println("You have won the game");
            break;
              }
            
                        if((mhs-myStr-a) <= 0)
              {
            System.out.println("I have won the game");
            break;
               }
      }
       }
}

Thanks again for your help. I apprecaite it alot

try this:


while(mhs > 0)
             {
             System.out.println("Your move first. How many stick do you take");
             meString = stdin.readLine();
             int myStr = Integer.parseInt(meString);
             
             if((mhs-myStr) <= 0)
             {
                   System.out.println("YOU win the game");
                   break;
             }

             int spt = Integer.parseInt(strSticksPerTurn);
             Random rnd = new Random();
             int a = rnd.nextInt(spt);

             System.out.println("That leaves " +(mhs-myStr)+ " sticks. I pick up " +a+ ". " +(mhs-myStr-a)+ " sticks remain.");
             mhs = mhs-myStr-a;
         
             if(mhs <= 0)
             {
                      System.out.println("I have won the game");
                      break;
             }
           }
sorry i realized what the problem was .. i forgot to tell you. The problem was that I had to put the if-statements befoe this line "mhs = mhs-myStr-a;" Sorry. But I do have another problems(s). Whats new .. right? Anyway. I am trying to make a code for the comptuer part like whenever the computer goes first. I have this code but for some reason whenever I type YOU for the question "WHo wants to go first?" .. the program stalls .. it does not go any furhter. Here is the code. The difference in the computer part is that the computer goes first so I can't ask the user to enter the data first. But here the code .. the it same as before .. just a slide modification:

if ((confirmOkay.equals("okay")) && (strFirstPlayer.equals("YOU")))
   {
        int mhs = Integer.parseInt(strHowManySticks);
        meString = stdin.readLine();
        int myStr = Integer.parseInt(meString);
 
       int spt = Integer.parseInt(strSticksPerTurn);
       Random rnd = new Random();
       int a = rnd.nextInt(spt);

       System.out.println("That leaves " +mhs+ " sticks. I pick up " +a+ ". "
               +(mhs-myStr-a)+" sticks remain.\n");

       while(mhs > 0)
      {
      System.out.println("Your move. How many stick do you take");

                System.out.println("That leaves " +(mhs-myStr)+ " sticks. I pick up " +a+ ". "
                                          +(mhs-myStr-a)+" sticks remain.\n");

                if((mhs-myStr) == 0)
      {
            System.out.println("You have won the game");
            break;
      }
      
      if((mhs-myStr-a) <= 0)
      {
                System.out.println("I have won the game");
           break;
      }
       mhs = mhs-myStr-a;
        }
 }
You didnt post the part of your code that stalls.
That is the code where nothing happens. It compiles and everything but it stops workin' when I choose YOU (for the computer to go first) I am gonna post the whole code:

import java.net.*;
import java.util.Random;
import java.io.*;
import java.awt.*;

public class KnockKnockProtocol
{
    public String processInput(String theInput)
    {
            String theOutput = null;

            String strHowManySticks     = "";
            String strSticksPerTurn = "";
            String strFirstPlayer = "";
            String confirmOkay = "";
            String meString = "";
            String compString = "";

             try
             {
               BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) );
               System.out.println("MESSAGE FROM SERVER: Let's Play NIM. Whoever Picks the last stick wins. Let's \n"
                             + "decide the rules. How many sticks do you want ot play with?");
               System.out.print("INPUT: ");
               strHowManySticks = stdin.readLine();

               System.out.println("SERVER: How many sticks can we pick per turn? ");
               System.out.print("INPUT: ");
               strSticksPerTurn = stdin.readLine();


               System.out.println("SERVER: Who should go first? (YOU or ME)");
               System.out.print("INPUT: ");
               strFirstPlayer = stdin.readLine();

               System.out.println("SERVER: The rules are " + strHowManySticks + " sticks, " + strSticksPerTurn +
                                  " max sticks per move. okay?");
               System.out.print("INPUT: ");
               confirmOkay = stdin.readLine();

               if ((confirmOkay.equals("okay")) && (strFirstPlayer.equals("ME")))
               {

                                       int mhs = Integer.parseInt(strHowManySticks);

                                while(mhs > 0)
                                 {

                                      
                                      System.out.println("SERVER: Your move. How many sticks do you take?");
                                      System.out.print("INPUT: ");
                                      meString = stdin.readLine();
                                      int myStr = Integer.parseInt(meString);
                                          

                                      int spt = Integer.parseInt(strSticksPerTurn);
                                      Random rnd = new Random();
                                      int a = rnd.nextInt(spt);

                                      System.out.println("SERVER: That leaves " +(mhs-myStr)+ " sticks. I pick up " +a+ ". "
                                                                 +(mhs-myStr-a)+" sticks remain.");

                                      if((mhs-myStr) == 0)
                                      {
                                                System.out.println("You have won the game");
                                                break;
                                          }
                                          if((mhs-myStr-a) == 0)
                                          {
                                                System.out.println("I have won the game");
                                                break;
                                          }

                                      mhs = mhs-myStr-a;
                                    }

                   }

               if ((confirmOkay.equals("okay")) && (strFirstPlayer.equals("YOU")))
               {

                                       int mhs = Integer.parseInt(strHowManySticks);

                                       meString = stdin.readLine();
                                 int myStr = Integer.parseInt(meString);

                                 int spt = Integer.parseInt(strSticksPerTurn);
                                 Random rnd = new Random();
                                 int a = rnd.nextInt(spt);

                                 System.out.println("That leaves " +mhs+ " sticks. I pick up " +a+ ". "
                                                             +(mhs-a)+" sticks remain.\n");

                                while(mhs > 0)
                                 {
                                      System.out.println("Your move. How many stick do you take");

                                      System.out.println("That leaves " +(mhs-myStr)+ " sticks. I pick up " +a+ ". "
                                                                 +(mhs-myStr-a)+" sticks remain.\n");

                                      if((mhs-myStr) == 0)
                                      {
                                                System.out.println("You have won the game");
                                                break;
                                          }
                                          if((mhs-myStr-a) <= 0)
                                          {
                                                System.out.println("I have won the game");
                                                break;
                                          }

                                      mhs = mhs-myStr-a;
                                    }

                   }

             }
             catch ( IOException iox )
             {
               System.out.println("Problem reading "  );
             }



        return theOutput;
    }
}


If you want to run this .. you need the server and client codes I have on the top. Thanks
That code doesnt hang at all.
Make sure you input "YOU" with capitals, since that is the way you have it coded.
I am gonna try to see if there is something wrong on my part. Thanks

I am trying to do an error check for this part of the code but it doens't work out too fine

while ((strFirstPlayer != "YOU") || (strFirstPlayer != "ME"))
{                
  System.out.println("SERVER: Who should go first? (YOU or ME)");
  System.out.print("INPUT: ");
  strFirstPlayer = stdin.readLine();
}

but it doesn't work because the variable strFirstPlayer is a string .. i know how to compare strings by using .equals but I gotta make it so this doesn't equal so the loop can go over and over again until the use chooses either You or Me. Thanks for the help again
alright another question ... for the computer part. I need the program to let the computer choose the numbers first if the computer goes first to pick the numbers but I can't do that or unable to find how to do that for some dumb reason.

               if ((confirmOkay.equals("okay")) && (strFirstPlayer.equals("YOU")))
               {

                                  int mhs = Integer.parseInt(strHowManySticks);
                                  int myStr;

                                  int spt = Integer.parseInt(strSticksPerTurn);
                                 Random rnd = new Random();
                                 int a = rnd.nextInt(spt);

                               System.out.println("SERVER: That leaves " +(myStr)+ " sticks. I pick up " +a+ ". "
                                                                 +(myStr-a)+" sticks remain.");

                                while(mhs > 0)
                                 {

                                      System.out.println("SERVER: Your move. How many sticks do you take?");
                                      System.out.print("INPUT: ");
                                      meString = stdin.readLine();
                                      myStr = Integer.parseInt(meString);

                                      System.out.println("SERVER: That leaves " +(mhs-myStr)+ " sticks. I pick up " +a+ ". "
                                                                 +(mhs-myStr-a)+" sticks remain.");

                                      if((mhs-myStr) == 0)
                                      {
                                                System.out.println("You have won the game");
                                                break;
                                          }
                                          if((mhs-myStr-a) == 0)
                                          {
                                                System.out.println("I have won the game");
                                                break;
                                          }

                                      mhs = mhs-myStr-a;
                                    }

                   }

It gives me this error when I try to do that:
C:\Param's Stuff\Second Year at R.I.T\Computer Programming 3\crap\2\KnockKnockProtocol.java:94: variable myStr might not have been initialized
                               System.out.println("SERVER: That leaves " +(myStr)+ " sticks. I pick up " +a+ ". "
                                                                                                                            ^
change to
while (!strFirstPlayer.equals("YOU") && !strFirstPlayer.equals("ME"))
the reason you are getting that error simple.  You have:

int myStr;
// Ok, you declare an int myStr

System.out.println("SERVER: That leaves " +(myStr)+ " sticks. I pick up " +a+ ". "+(myStr-a)+" sticks remain.");
// Now you just tried to print out the value of myStr.  You cant do this because you never assigned a value to it!!!
Yes I understand that but how can I fix that problem ... Thanks
any suggestions to how can I fix that problem. Thanks
ASKER CERTIFIED SOLUTION
Avatar of lwinkenb
lwinkenb

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
alright sorry .. that was just a stupid question ... Sorry. But I got a few more questions real quick.

Here is the code when the computer goes first:
 if ((confirmOkay.equalsIgnoreCase("okay")) && (strFirstPlayer.equalsIgnoreCase("YOU")))
               {

                                  int spt = 0;
                                  int a = 0;

                                  int mhs = Integer.parseInt(strHowManySticks);

                                  spt = Integer.parseInt(strSticksPerTurn);
                                 Random rnd = new Random();
                                 a = rnd.nextInt(spt);
                                 //int a = rnd.nextInt(mhs % (spt + 1));

                               System.out.println("SERVER: That leaves " +(mhs)+ " sticks. I pick up " +a+ ". "
                                                                 +(mhs-a)+" sticks remain.");

                                while(mhs > 0)
                                 {
                                           System.out.println("\nSERVER: Your move. How many sticks do you take?");
                                      System.out.print("INPUT: ");
                                      meString = stdin.readLine();
                                      int myStr = Integer.parseInt(meString);

                                      spt = Integer.parseInt(strSticksPerTurn);
                                          Random rnd2 = new Random();
                                      a = rnd2.nextInt(spt);

                                      System.out.println("SERVER: That leaves " +(mhs-myStr)+ " sticks. I pick up " +a+ ". "
                                                                 +(mhs-myStr-a)+" sticks remain.");

                                      if((mhs-myStr) == 0)
                                      {
                                                System.out.println("You have won the game");
                                                break;
                                          }
                                          if((mhs-myStr-a) == 0)
                                          {
                                                System.out.println("I have won the game");
                                                break;
                                          }

                                      mhs = mhs-myStr-a;
                                    }
                   }

and here is the output that it gives me (which is wrong):
MESSAGE FROM SERVER: Let's Play NIM. Whoever Picks the last stick wins. Let's
decide the rules. How many sticks do you want to play with?
INPUT: 20

SERVER: How many sticks can we pick per turn?
INPUT: 5

SERVER: Who should go first? (YOU or ME)
INPUT: you

SERVER: The rules are 20 sticks, 5 max sticks per move. okay?
INPUT: okay
SERVER: That leaves 20 sticks. I pick up 3. 17 sticks remain.

SERVER: Your move. How many sticks do you take?
INPUT: 4
SERVER: That leaves 16 sticks. I pick up 2. 14 sticks remain.

SERVER: Your move. How many sticks do you take?
INPUT:

As you can seee .. the computer goes first but when I enter an input of 4 sticks to be taken out .. the server says it leaves 16 sticks in which it should be 13. I don't know what is causing this. Thanks

The other question is that I am try to do an error check for this part of the code:
             System.out.println("\nSERVER: Your move. How many sticks do you take?");
                                 System.out.print("INPUT: ");
                                 meString = stdin.readLine();
                                 int myStr = Integer.parseInt(meString);

I have to make it sure that the user only picks between the amount specified when he or she is asked to enter the amount of sticks picked up per turn. I tried many things ... as always .. it won't cooperate. Thanks for your help
Alright another question added to the top one about error checking for this code of line:
                                 do
                                 {
                                 System.out.println("\nSERVER: That leaves " +(mhs-myStr)+ " sticks. I pick up " +a+ ". "
                                                    +(mhs-myStr-a)+" sticks remain. ");
            }while(((mhs-myStr)-myStr) <= 0);
            
What I want to do is that I need to check if the user is inputting the right amount of sticks to be taken out. For example, if there is only 2 sticks remaning and the user puts in 3. I want the program to keep repeatin the line until he puts in the right number which will equal to zero. I dont' want a negative number of sticks remaing.

These are the only questions that I have. Thanks for all your help
Thanks for your help. I got fed up with the program. I finally gave it in. Everything worked except for the few error checks which i couldn't get to work at all ... oh well. THanks agian