Wafi Ismail Wafi Ismail - 4 months ago 24
Java Question

Print out variable from another class?

this class

Time
:

public class Time {

int secondPassed = 0;
Timer mytime = new Timer()

TimerTask mytask = new TimerTask() {
public void run() {
secondPassed++;

if(secondPassed == 3) {
secondPassed = 0;

Udp callUdp = new Udp();
String trnsferRP = callUdp.trnsfrRPckt();
System.out.println(trnsferRP + "exp");
System.out.println("Its 10");
}
else {
System.out.println("Second : " + secondPassed);
}
}
};

public void start(){
mytime.scheduleAtFixedRate(mytask, 1000,1000);
}

public static void main(String[] args) throws Exception {
Time starter = new Time();
starter.start();
}
}


this is class
UDP
:

public class Udp {

public DatagramPacket receivePacket;
public String result;

public void socketp() throws Exception {
DatagramSocket clientSocket = new DatagramSocket(10076);
InetAddress IPAddress = InetAddress.getByName("192.168.100.10");
byte[] sendData = new byte[9];
byte[] receiveData = new byte[9];
String sentence = "VDV2bE1";
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 10076);
clientSocket.send(sendPacket);
this.receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
clientSocket.close();
this.result = new String(receivePacket.getData());
return;
}

public String trnsfrRPckt(){
return this.result;
}
}


so I'm trying to call a variable from
class Udp
to
class Time
, by that I'm want to print the packet received. Currently my result is:

second : 1
second : 2
nullexp
its 10


why null came out? should be a packet data + "exp"

Answer

You never called

callUdp.socketp();

Which is the only function that write to result variable. So your result is null until you have a call to socketp().