4 Replies - 295 Views - Last Post: 26 April 2019 - 02:38 PM Rate Topic: -----

#1 Grimmjow91   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 20-February 19

Java losing variables during second loop iteration.

Posted 25 April 2019 - 05:54 PM

I am working on a programming lab, it isn't graded, just something for us to practice multi-threading. I have an odd issue I have not seen before and I am confused on what caused it. So I have a program that is a server and then I have a program for the client. The server starts a thread every time there is a connection from a client program, and the thread ends when the client program ends. The client gets the users name, sends it to the server, the server counts how long it is, and then send back the length. The client will then show the user the length of their name, and ask if the user wants to continue, if the user types 1 it loops. If they type anything else the client exits. If the user types 1, that 1 is send to the server to tell it to loop again. First time it runs, it is fine second time it freezes.

I have done step by step debugging on my server to see the values, in the first loop, cMess doesn't show up until something is assigned to it, same with loop, but all the variable work like they are supposed to. However when the user decides to loop, the variables cMess and loop are removed from the variable list. However my PrinterWriter and BufferedReader are still there but cMess and loop are not. When the server gets to the line
cMess = in.readLine();
it won't run and just freezes. I am confused as to why this it. Could someone explain what is going on and what I need to do in order to fix it.

server
package mserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MServer implements Runnable {

    Socket socket;

    MServer(Socket socket) {//this is the constructor to make the server Objects that we can run. 
        this.socket = socket;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8000);
        while (true) {
            Socket socket = server.accept();
            MServer c = new MServer(socket);
            Thread t = new Thread(c);
            t.start();
        }
    }

    @Override
    @SuppressWarnings("empty-statement")
    public void run() {
        //this is going to be what is running on the server. 

        PrintWriter out;
        BufferedReader in;

        try {
            boolean loop = false;
            String cMess; //this is going to hold the message of the client.

            int lName; //this is the length of the name. 
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            do {

                System.out.println("do it");

                cMess = in.readLine();
                System.out.println("got it");
                lName = cMess.length();
                System.out.println("math it = " + lName);
                out.println(lName);
                System.out.println("sent it");
                cMess = in.readLine();
                System.out.println("got it");
                loop = Integer.parseInt(cMess) == 1;

            } while (loop);

        } catch (Exception e) {

        }

    }//end of run
}//end of class




client

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class MClient {
    public static void main(String[] args) throws IOException {
       Scanner input = new Scanner (System.in);
       String sResponse; //this is going to be the response from the server
       String name; //this is going to be the name provided by the user. 
       int userChoice; //this is going to allow the user to choose if they want
        //to continue talking to the server. 
        Socket socket = new Socket("localhost",8000); //this connects to the server. 
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        
        do{
            System.out.println("Please enter your name:");
            name = input.nextLine();          
            out.println(name);
            sResponse = in.readLine();
            System.out.println("got it");
            System.out.println("Your name: " + name + ", is " + sResponse + " characters long");                      
            System.out.println("Please enter 1 to continue or any other number to exit.");
            userChoice = input.nextInt();
            out.print(userChoice);
            
                 
        }while(userChoice == 1);
        
    }
    
}




Is This A Good Question/Topic? 0
  • +

Replies To: Java losing variables during second loop iteration.

#2 Jordy2254   User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 58
  • Joined: 18-October 14

Re: Java losing variables during second loop iteration.

Posted 26 April 2019 - 12:40 PM

Hello,

Firstly I'd like to start by just saying using do while loops are bad practice when it comes to industry, think of it from the standpoint of a larger file where you then have to scroll down to find the while loop it makes the reading process longer from a 3rd party prospective. Just so your aware if your going into industry.

Secondly onto the problem itself:

Looking at the code on the server to the client appears ok to beging with however:

Buffer streams are wrong, going through your program structure line 35 your using "print" rather than "println" this means that within server code when your using the readline() on line 56 because the line hasn't ended on the socket yet it doesn't detect it making this one change should allow you to have the program functioning as you should.

I also pressume you realise that at no point is the number validated, if your awear of this fine, if not client side needs to validate than the input is a number before sending it to the server otherwise it is going to crash the server when converting it into an integer. the other way around this is surround the value with a try catch and if fall in the catch block then don't loop


Hope this helps

Jordan
Was This Post Helpful? 1
  • +
  • -

#3 xclite   User is offline

  • I wrote you an code
  • member icon


Reputation: 1380
  • View blog
  • Posts: 4,206
  • Joined: 12-May 09

Re: Java losing variables during second loop iteration.

Posted 26 April 2019 - 12:45 PM

View PostJordy2254, on 26 April 2019 - 03:40 PM, said:

Hello,

Firstly I'd like to start by just saying using do while loops are bad practice when it comes to industry, think of it from the standpoint of a larger file where you then have to scroll down to find the while loop it makes the reading process longer from a 3rd party prospective. Just so your aware if your going into industry.


This... isn't really true. There are a lot of cases where you'd want to use a do/while loop. The real issue would be the size of the body of the loop - it should be easy to see what's being done in a loop. This isn't specific to do/while loops.
Was This Post Helpful? 0
  • +
  • -

#4 Jordy2254   User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 58
  • Joined: 18-October 14

Re: Java losing variables during second loop iteration.

Posted 26 April 2019 - 01:41 PM

View Postxclite, on 26 April 2019 - 12:45 PM, said:

This... isn't really true. There are a lot of cases where you'd want to use a do/while loop. The real issue would be the size of the body of the loop - it should be easy to see what's being done in a loop. This isn't specific to do/while loops.


Our techincal expierence differ's slightly then, I've always been taught that it's frowned upon, but different companies and standards and even styles have there own ways of doing things. However that wasn't the focus of my answer, the focus of my answer was the fix for the solution the OP posted.

This post has been edited by Jordy2254: 26 April 2019 - 01:41 PM

Was This Post Helpful? 0
  • +
  • -

#5 Grimmjow91   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 20-February 19

Re: Java losing variables during second loop iteration.

Posted 26 April 2019 - 02:38 PM

View PostJordy2254, on 26 April 2019 - 12:40 PM, said:

Hello,

Firstly I'd like to start by just saying using do while loops are bad practice when it comes to industry, think of it from the standpoint of a larger file where you then have to scroll down to find the while loop it makes the reading process longer from a 3rd party prospective. Just so your aware if your going into industry.

Secondly onto the problem itself:

Looking at the code on the server to the client appears ok to beging with however:

Buffer streams are wrong, going through your program structure line 35 your using "print" rather than "println" this means that within server code when your using the readline() on line 56 because the line hasn't ended on the socket yet it doesn't detect it making this one change should allow you to have the program functioning as you should.

I also pressume you realise that at no point is the number validated, if your awear of this fine, if not client side needs to validate than the input is a number before sending it to the server otherwise it is going to crash the server when converting it into an integer. the other way around this is surround the value with a try catch and if fall in the catch block then don't loop


Hope this helps

Jordan



It helped a lot and not only does it work, I understand why it didn't work before. I know the number isn't being validated, this isn't really a program that is meant to be used but just something super simple to practice threads is all. I actually didn't know that some places don't like do whiles thank you for that inside. I don't use them very often even so thank you very much for that insight so I will now know to look out for that.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1