[英]Why is the Scanner not working properly in Java?
因此,我正在用Java編寫一個Client-Server程序,該程序專注於更改服務器上的數據。 這是客戶端的代碼:
package com.company;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args){
try {
DatagramSocket socket=new DatagramSocket(4001);
while(true){
Scanner jin=new Scanner(System.in);
String text=jin.nextLine();
byte[] word=new byte[256];
int command=Integer.parseInt(text);
word=text.getBytes();
DatagramPacket packet=new DatagramPacket(word, word.length, InetAddress.getByName("localhost"), 4000);
socket.send(packet);
if (command==0){
word=new byte[256];
packet=new DatagramPacket(word, word.length);
socket.receive(packet);
word=packet.getData();
System.out.println(new String(word));
}
else if (command==1){
word=new byte[256];
packet=new DatagramPacket(word, word.length);
socket.receive(packet);
System.out.println(new String(word));
int broj=jin.nextInt();
word=Integer.toString(broj).getBytes();
packet=new DatagramPacket(word, word.length, InetAddress.getByName("localhost"), 4000);
socket.send(packet);
word=new byte[256];
packet=new DatagramPacket(word, word.length);
socket.receive(packet);
System.out.println(new String(word));
new ClientHandler(socket).start();
}
else if(command==2){
word=new byte[256];
packet=new DatagramPacket(word, word.length);
socket.receive(packet);
System.out.println(new String(word));
jin=new Scanner(System.in);
int broj=Integer.parseInt(jin.next());
System.out.println("Test");
byte[] word1=Integer.toString(broj).getBytes();
System.out.println(new String(word1));
packet=new DatagramPacket(word1, word1.length, InetAddress.getByName("localhost"), 4000);
socket.send(packet);
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
問題出在if語句中,其中:
else if (command==2)
輸入有效數字后,程序不會繼續前進。 經過一些調試后,我發現問題出在掃描儀上:
int broj=Integer.parseInt(jin.next());
掃描儀未注冊輸入的值,並且不打印“ test”,並且程序被卡住。 有人知道解決方案嗎?
您不止一次使用Scanner; 不好 擁有一台掃描儀(在while循環之外創建)。
不要混合使用nextLine
和其他next方法。 要么只使用nextLine,要么永遠不使用nextLine。 如果要獲取“下一個字符串,直到換行符”(與“下一個字符串,直到空格,這是next()
通常所做的一樣)”,請設置定界符: scanner.useDelimiter("\\r?\\n")
制作掃描儀后立即意味着next()
現在將抓取整行。
注意:您通常會看到有關在非下一個調用之后再添加一個nextLine
建議。 這是非常普遍的,但建議不正確。 如上所述,改正定界符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.