我有我正在研究的這個程式。在Java socket程式和網路方面我不是很中級,但我這里有個小錯誤,看看:
服務器類:
import java.net.*;
import java.io.*;
import java.util.*;
public class MyEchoServer {
public static void main(String[] args) throws Exception{
ServerSocket ss = new ServerSocket(6807);
System.out.println("MyEchoServer is Running");
System.out.println("Waiting for the client to connect...");
Socket s = ss.accept();
Scanner sc = new Scanner(s.getInputStream());
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
String str="";
Integer age=1;
while(age!=0) {
str=sc.nextLine();
age = Integer.parseInt(str);
pw.println(2022-age);
}
s.close();
}
}
客戶端類:
import java.net.*;
import java.io.*;
import java.util.*;
public class MyEchoClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost",6246);
Scanner sc = new Scanner(s.getInputStream());
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
Scanner in = new Scanner(System.in);
String str="";
Integer age=1;
while(age!=0) {
System.out.println("Enter Age");
str=in.nextLine();
age = Integer.parseInt(str);
pw.println(age);
str=sc.nextLine();
System.out.println(str);
}
System.out.println("Exiting...");
s.close();
}
}
輸出 :
Enter Age
10
2012
Enter Age
0
2022
Exiting...
問題是,在說0退出程式之后,它還列印了獲取年齡的方程。
這可能是一個簡單的錯誤,對于體面的程式員來說會很有趣,但我已經嘗試編輯了幾個小時,但無法想出一個主意。
問題可能在while回圈中,但我無法理解它。
uj5u.com熱心網友回復:
問題是,在說
0退出程式之后,它還列印了獲取年齡的方程。
那是因為無論輸入值實際是什么,您都在執行計算并列印結果。您需要先查看輸入值,然后采取相應措施,例如:
服務器類:
import java.net.*;
import java.io.*;
import java.util.*;
public class MyEchoServer {
public static void main(String[] args) throws Exception{
ServerSocket ss = new ServerSocket(6807);
System.out.println("MyEchoServer is Running");
System.out.println("Waiting for the client to connect...");
Socket s = ss.accept();
Scanner sc = new Scanner(s.getInputStream());
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
do {
String str = sc.nextLine();
int age = Integer.parseInt(str);
if (age == 0) break; // <-- add this!
pw.println(2022-age);
}
while (true);
s.close();
}
}
客戶端類:
import java.net.*;
import java.io.*;
import java.util.*;
public class MyEchoClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost",6246);
Scanner sc = new Scanner(s.getInputStream());
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
Scanner in = new Scanner(System.in);
do {
System.out.println("Enter Age");
String str = in.nextLine();
int age = Integer.parseInt(str);
pw.println(age);
if (age == 0) break; // <-- add this!
str = sc.nextLine();
System.out.println(str);
}
while (true);
System.out.println("Exiting...");
s.close();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/520777.html
標籤:爪哇插座
下一篇:有沒有辦法減少冗余?
