本文介绍了Java应用程序挂在in.hasNext();上.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究通过套接字进行通信的Battleship swing应用.

I am working on Battleship swing app that communicates through sockets.

private ServerSocket server;
private Socket connection;
private PrintWriter out;
private Scanner in;

我建立连接并设置输出和输入流

I make a connection and setup output and input streams

out = new PrintWriter(connection.getOutputStream(), true);
in = new Scanner(connection.getInputStream());

然后用户单击他认为有船的字段,并发送坐标

Then user clicks on field that he thinks there is a ship, and coordinates get sent

public void sendXY(String cord)
{
    out.print(cord);
}

然后调用该方法,以等待对手的应用程序是否响应(真|假).

Then the method gets called that waits for opponents app to respond if there is a ship or not (true|false).

public void readHit()
{
    boolean k = true;
    while(k)
    {
        if(in.hasNext()) //<--app hangs at this line
        {
            Fields.hit = in.nextBoolean();
            k = false;
        }
    }
}

但是当我对此进行测试时,我的应用程序在首次调用in.hasNext()时挂起.

But when I test this, my app hangs at first call to in.hasNext().

推荐答案

扫描程序正在等待令牌,除非String cord包含某种终止符,否则打印方法不会发送完整的令牌.尝试改用println.

The scanner is waiting for a token, the print method does not send a complete token unless String cord contains some kind of terminator. Try to use println instead.

这篇关于Java应用程序挂在in.hasNext();上.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 00:40