For或While循环跳过输入

时间:2012-10-09 15:15:22

标签: java loops fencepost

  

可能重复:
  Scanner issue when using nextLine after nextInt

我正在创建一个客户端程序,需要从我的服务器读取字符串和整数。根据它接收的整数,它会向GUI添加一些标签。到目前为止,我的程序读取整数但跳过字符串。当我尝试将整数写入程序时,以下输出是我程序的输出:

  • 服务器写道:1
  • 服务器写道:1
  • 系统打印:1
  • 系统打印:j1
  • 系统打印:名称

问题是我无法编写String,因为它会跳过String。如何避免此问题(请注意,我还尝试了for循环)

我的代码如下:

int times = client.reciveCommando();
int o = 0;
System.out.println(times);

while (o != times) {
  int j = client.reciveCommando();
  System.out.println("j"+ j);
  String name = client.reciveString();
  System.out.println("Name " +name);
  createUser(j, name);
  o++;

}

createUser方法:

private void createUser(int j, String reciveChat) {
  if (j == 1) {
    chatPerson1.setVisible(true);
    lbl_Chatperson1_userName.setVisible(true);
    lbl_Chatperson1_userName.setText(reciveChat);
  } else if (j == 2) {
    lbl_chatPerson2.setVisible(true);
    lbl_userName2.setVisible(true);
    lbl_userName2.setText(reciveChat);
  } else {
    chatPerson3.setVisible(true);
    lbl_userName3.setVisible(true);
    lbl_userName3.setText(reciveChat);
  }
}

client.reciveCommando方法:

public int reciveCommando() throws IOException{
  Integer i = input.nextInt();
  return i;
}

client.reciveString方法:

public String reciveString(){
  String x = input.nextLine();
  return x;
}

希望有人能够帮助我:)

提前谢谢。

2 个答案:

答案 0 :(得分:1)

我没有在循环代码中看到您正在递增o或更改times的值的任何位置。因此,要么完全跳过循环(即:times = 0),要么代码中的其他位置正在修改循环变量(o)或循环条件(times) - 非常糟糕的编码在任何一种情况下。

你的循环变量/增量规则在读取循环时应该非常清楚,并且很容易辨别启动/停止条件是什么,而不需要读取可能在循环迭代期间修改值的其他方法/等。

我的直接猜测是times = 0,或者你将处于无休止的循环中。

答案 1 :(得分:0)

我发现问题的解决方案结果非常简单!

首先让我解释一下我的想法。

当我的程序运行while循环时,它基本上跳过应该从服务器接收输入的行。我发现它的原因是input.nextLine();当你为input.nextLine()读取api时,它是空的。

  

使此扫描程序超过当前行并返回跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。该位置设置为下一行的开头。   由于此方法继续搜索输入以查找行分隔符,因此如果不存在行分隔符,则它可以缓冲搜索要跳过的行的所有输入。   返回:   被跳过的行

因为我试图获得的行是一个空行,所以它会跳过并将名称设置为“”。

这是我的程序的完整代码,目前有效:

while循环:

            while (o != times) {
                int j = client.reciveCommando();
                System.out.println("j"+ j);
                    String name = client.reciveString();
                    System.out.println("Name " +name);
                    createUser(j, name);    
                o++;
            }

client.reciveString();

    public String reciveString(){

    String x = input.next();
    return x;
}

createUser();

    private void createUser(int j, String reciveChat) {
    if (j == 1) {
        chatPerson1.setVisible(true);
        lbl_Chatperson1_userName.setVisible(true);
        lbl_Chatperson1_userName.setText(reciveChat);

    }else if (j == 2) {
        lbl_chatPerson2.setVisible(true);
        lbl_userName2.setVisible(true);
        lbl_userName2.setText(reciveChat);
    }else if (j == 3){
        chatPerson3.setVisible(true);
        lbl_userName3.setVisible(true);
        lbl_userName3.setText(reciveChat);}

感谢您的所有回复,我一定会投票给您:)

相关问题