So I'm making a Client-Server program in java that is focused on changing data on the server. Here is the code for the client side:
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();
}
}
}
The problem lies in the if statement where:
else if (command==2)
After I enter a valid number the program doesn't move forward. After some debugging I found out that the problem lies in the Scanner or:
int broj=Integer.parseInt(jin.next());
The scanner doesn't register the inputted value and doesn't print "test" and the program gets stuck. Anyone know a solution?