可能重複:
Scanner issue when using nextLine after nextIntfor或while循環跳過輸入
我創建需要同時讀取一個String並從我的服務器整數的客戶端程序。取決於它接收到的整數,它向GUI添加了一些標籤。到目前爲止,我的程序讀取整數,但跳過字符串。下面的輸出是我的程序的輸出,當我嘗試寫整數程序:
- Server寫入:1
- Server寫入:1個
- 系統打印:1
- 系統打印:J1
- 系統打印:名稱
問題是我無法寫入字符串,因爲它跳過字符串。我怎樣才能避免這種問題(請注意,我也嘗試了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;
}
希望有人能夠幫助我解決這個:)
預先感謝您。
你在哪裏增加Ø? (也許我是盲目的?)如果時間== 0,你的while循環會跳過一個字符串。 – belwood
可能這是你正在尋找或者它可以幫助你。 http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextint – Abubakkar