Note that there are some explanatory texts on larger screens.

plurals
  1. POjava multi-thread and object
    primarykey
    data
    text
    <p>I have three classes. When the server starts, it creates a randomGame object with a guessCount and random number. When the client starts, it connects to the server and passes the number to server to play the guess method(with console input number) to guess the random number of the randomGame generated.</p> <p>But the following has problems. The client enter the number each time, the guessCount &amp; the random number are reinitialized(that is, the random number is different and guessCount can't increment). I want the random number to be the same for each client program running and the guessCount will be incremented by 1 each time when the guess method run.</p> <pre><code>public class Game { private int num; private int guessCount; Game (int num) { this.num = num; System.out.println("guessCount = " + guessCount); System.out.println("num = " + num); } public int guess (int ran) { int result; guessCount++; if (this.guessCount &gt;= 10) { return -2; } else if (ran &lt; num) { return -1; } else if (ran &gt; num) { return 1; } else { return 0; } } } </code></pre> <p>Here's <code>RandomGame</code></p> <pre><code>class RandomGame extends Game { RandomGame () { super(0 + (int)(Math.random() * ((90 - (0)) + 1))); } public static void main (String args[]) { } } </code></pre> <p>Here's the server:</p> <pre><code>import java.io.*; import java.net.*; public class Q4Server { public static void main(String arg[]) { try { ServerSocket ss = new ServerSocket(12345); while(true) { Socket s = ss.accept(); ClientHandler ch = new ClientHandler(s); ch.start(); } } catch(IOException ioe) { ioe.printStackTrace(); } } } </code></pre> <p>Here's the client handler:</p> <pre><code>class ClientHandler extends Thread { Socket socket; RandomGame g; public ClientHandler(Socket socket) { this.socket = socket; g = new RandomGame(); } public void run() { try { DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); int x = dis.readInt(); int reply = this.g.guess(x); System.out.println("reply = " + reply); dos.writeInt(reply); //System.out.println(reply); //System.out.println(reply); socket.close(); } catch(IOException ioe) { ioe.printStackTrace(); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload