n00bie1221 n00bie1221 - 1 month ago 15
Java Question

Java Increment issues

Within my while loop below i get an syntax error under "+=". I went here but the answer didnt help me.

Cumulative sum of an Array

I am just trying to print each cumulative sum that is being streamed from the Server.

public static void main(String[] args) {

try
{
//Create client socket, connect to server
Socket clientSocket = new Socket("localhost",9999);
//create output stream attached to socket
PrintStream outToServer = new PrintStream(clientSocket.getOutputStream());

System.out.print("Command : ");
//create input stream
InputStreamReader inFromUser = new InputStreamReader(System.in);
BufferedReader ed = new BufferedReader(inFromUser);

String temp = ed.readLine();

outToServer.println(temp);
//create input stream attached to socket
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

String display=null;
while((display = inFromServer.readLine())!=null){
int displayByt = Integer.valueOf(display);
double totalByt += displayByt;//SYNTAX ERROR "+="
//totalByt = totalByt + displayByt; Does not Work either
System.out.print(totalByt);
System.out.print("\n");
}
clientSocket.close();
}

Answer

You should define and initialize totalByt before the loop, and only add to it in the loop, not attempt to redefine it:

double totalByt = 0.0; // Defined and initialized here
while ((display = inFromServer.readLine()) != null) {
    int displayByt = Integer.valueOf(display);
    totalByt += displayByt; // Used here
}
Comments