Article

Number Guessing Game In Java With Source Code

by FHTE

In this post, I will be sharing the number guessing game in java with source code. As the name suggests, the player needs to guess the number between two given numbers. This game is played between 2 or more players. In this number guessing game, the computer will pick the SECRET number and the player who should find this SECRET number within a given number of tries. Let's understand the rules of the game first before moving on to the algorithm and java program

public class client {
    public static void main(String[] args) throws IOException {
        Socket s= new Socket("localhost",8000);
        System.out.println("connect is OK!!!!");
        DataInputStream din = new DataInputStream(s.getInputStream());
          DataOutputStream dout =new DataOutputStream(s.getOutputStream());
          Scanner sr=new Scanner(System.in);
          while(true){
          String b=din.readUTF();
          System.out.println(b);
          int c=sr.nextInt();
          if(c!=0){
          dout.writeInt(c);
          }
          else if (c==0){
              dout.writeInt(c);
              break;
          }
          String a=din.readUTF();
          System.out.println(a);
          }
    }
}
public class Handler extends Thread {
    Socket s;
    public Handler(Socket s){
    this.s=s;
}
    public void run(){
        System.out.println("I am serving you!");
        DataInputStream din=null;
        DataOutputStream dout=null;
        try{
            din = new DataInputStream(this.s.getInputStream());
            dout=new DataOutputStream(this.s.getOutputStream());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        Random ran = new Random();
          int a=ran.nextInt(9)+1;
        while(true)
        {
            try{
              dout.writeUTF("Guess a number in 1~9(type 0 to stop the game)");
          int r=din.readInt();
          if(r==0)
          {
              break;
          }
          else if(r<a)
          {
            dout.writeUTF("The digit is too low.");
          }
          else if(r>a)
          {
            dout.writeUTF("The digit is too high.");
          }
          else if(r==a)
          {
            dout.writeUTF("You are right.");
          }
            } catch (IOException ex) {
                 ex.printStackTrace();
            }
        }
    }
}
public class MultiServer {
    public static void main(String[] args) throws IOException {
        int port =8000;

        ServerSocket server =new ServerSocket(port);
    Socket s;
    while(true){
        System.out.println("Server is ready");
        s=server.accept();
        Handler h= new Handler(s);
        h.start();
    }
    }
   
}


1 0
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT