gpt4 book ai didi

java - 我的 Java 网络项目中存在循环和流控制问题

转载 作者:行者123 更新时间:2023-12-01 12:01:07 25 4
gpt4 key购买 nike

我正在尝试编写一个猜数字游戏,它有一个客户端接受猜测并输出结果,还有一个服务器接收所述猜测,将它们与随机生成的数字进行比较,并告诉客户端猜测是否太高,低或正确。目前我只是不明白为什么服务器不回复客户端。我认为我在某个地方犯了流量控制错误,但我对我的错误在哪里感到困惑......非常感谢任何帮助!

客户:

public class Client {

public static void main(String[] args) throws IOException {
System.out.println("This is Number Guessing Game. \nChoose any number between 1 to 1000 : ");
Scanner s = new Scanner(System.in);



try {
Socket client = new Socket("localhost", 8093);



DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(client.getOutputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(
client.getInputStream()));

boolean haswon=false;
int i=0;

while(i<11){
i++;
int guess = s.nextInt();
out.writeInt(guess);
out.flush();

String result = in.readUTF();
System.out.println(result);
haswon = in.readBoolean();
if(haswon=true){
System.out.println("You Win! :D");
i=11;}else{continue;}


}

client.close();
System.out.println("Game over. Thank you");
System.exit(0);

}catch (IOException ioe) {
System.err.println(ioe);
}
}
}

服务器:

public class Server {

public static void main(String[] args) throws IOException {
ServerSocket socket = null;
Socket client = null;
boolean haswon;

int guess = 0;
int random = 0;
int timer = 0;
String end;
String lwrong;
String hwrong;
String win;


try {
socket = new ServerSocket(8093);
System.out.println("The server socket has started and ready to receive client connection.");
client = socket.accept();


DataInputStream input = new DataInputStream(new BufferedInputStream(
client.getInputStream()));
DataOutputStream output = new DataOutputStream(new BufferedOutputStream(
client.getOutputStream()));


while(timer<11){
guess = input.readInt();
random=(int)(Math.random()*100);
if (guess < random){
lwrong="Your guess was too low, try again.";
output.writeUTF(lwrong);
System.out.println("successh");
haswon=false;
output.writeBoolean(haswon);
timer++;
}else if(guess > random){
hwrong="Your guess was too high, try again";
output.writeUTF(hwrong);
System.out.println("successl");
haswon=false;
output.writeBoolean(haswon);
timer++;
}else if(guess==random){
win="Correct!";
output.writeUTF(win);
System.out.println("successw");
timer=8;
haswon=true;
output.writeBoolean(haswon);
output.flush();
timer++;
break;
}
continue;


}
while(timer==7){
end="Out of Guesses, the correct answer was: ";
output.writeUTF(end);
output.flush();
break;
}








} catch (IOException ioe) {
System.err.println("Error Connecting "+ ioe);
return;
}




client.close();
socket.close();
}

}

最佳答案

您需要在循环外生成随机数,否则每次猜测都会改变。写入字符串后,您还必须在服务器中使用 out.flush() - 仅在获胜情况下才这样做。 while(timer == 7)可以完全删除,此时执行时您可以无条件写入客户端。

关于java - 我的 Java 网络项目中存在循环和流控制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27973900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com