汉诺塔代码java 汉诺塔代码Java( 二 )


PrintStream printStream = new PrintStream(socket.getOutputStream());
Scanner scanner=new Scanner(System.in);
System.out.println("请输入盘子数(3-10),数字太大,运算时间就会太长可能会卡死 。");
printStream.print(scanner.nextInt());
printStream.println();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
System.out.println("客户端socket关闭");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class HanoiServer extends Thread {//服务器线程类
private ServerSocket serverSocket;
public HanoiServer() {
try {
this.serverSocket = new ServerSocket(8888);
} catch (IOException e) {
e.printStackTrace();
}
}
private void hanoi(int n, String from, String inter, String to, PrintStream printStream) {
if (n == 1) {
printStream.print("Disk 1 from " + from + " to " + to);
printStream.println();
} else {
hanoi(n - 1, from, to, inter, printStream);
printStream.print("Disk " + n + " from " + from + " to " + to);
printStream.println();
hanoi(n - 1, inter, from, to, printStream);
}
}
@Override
public void run() {
Socket socket = null;
try {
socket = this.serverSocket.accept();
PrintStream printStream = new PrintStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int n = Integer.parseInt(reader.readLine());
this.hanoi(n, "A", "B", "C", printStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
System.out.println("服务器socket关闭");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
this.serverSocket.close();
System.out.println("服务器serverSocket关闭");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
【汉诺塔代码java 汉诺塔代码Java】汉诺塔代码java的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于汉诺塔代码Java、汉诺塔代码java的信息别忘了在本站进行查找喔 。

推荐阅读