在我的while循环中,我在“+ =”下遇到语法错误。我去了这里,但答案对我没有帮助 Cumulative sum of an Array
我只是想打印从服务器流式传输的每个累积总和。
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();
}
答案 0 :(得分:1)
您应该在循环之前定义并初始化totalByt
,并且只在循环中添加它,而不是尝试重新定义它:
double totalByt = 0.0; // Defined and initialized here
while ((display = inFromServer.readLine()) != null) {
int displayByt = Integer.valueOf(display);
totalByt += displayByt; // Used here
}
答案 1 :(得分:0)
在循环之前移动totalByt
的声明和初始化。在循环中增加它。并显示System.out.println
而不是两次调用print
。像,
double totalByt = 0; // <-- declare and set to 0.
while((display = inFromServer.readLine())!=null){
int displayByt = Integer.valueOf(display);
totalByt += displayByt;
System.out.println(totalByt);
}
答案 2 :(得分:0)
我认为这里唯一的问题是你的totalByt
变量需要一个初始值。基本上你的代码编写方式,你试图将整数添加到任何东西。
试试这个:
String display=null;
double totalByt = 0;
while((display = inFromServer.readLine())!=null){
int displayByt = Integer.valueOf(display);
totalByt += displayByt;
System.out.print(totalByt);
System.out.print("\n");
}
答案 3 :(得分:0)
初始化totalByt。这应该可以解决问题。