Plz help with Brick pi and java

Hello there,
im developing an autonomous motor with brick pi and ultrasonic sensor and i want to use java code to program it.
I already run the motors but I have a problem with the speed. when I set the motors speed to fixed numbers the function gives me random numbers between 0 and the number I put it. by the way, i’m using the source code that uploaded by dexter.
also, i want to know how to run the ultrasonic sensors with the motors so if there is an obstacles it will stop and change the direction.
I do this project as my bachelor project and im stuck here, so please help me. Thanks in advance.

no reply yet!!!

Do you have any example source code you’re having trouble with?

 Motor motor = new Motor();
motor.setCommandedOutput(0);
motor.setEnabled(true);
motor.resetEncoder();
brickPi.setMotor(motor, 0);
motor.setCommandedOutput(100);
for (int counter = 0; counter < 50; counter++) {
try {
System.out.println("Forward Motors: Speed " + brickPi.getMotor(0).getCurrentSpeed() + " encoder " + brickPi.getMotor(0).getCurrentEncoderValue() + " Time " + System.currentTimeMillis() % 10000);
Thread.sleep(200);
} catch (InterruptedException ex) {
// ignore
}
}
motor.setCommandedOutput(-25);
for (int counter = 0; counter < 50; counter++) {
try {
Thread.sleep(200);
System.out.println("Reverse Motors: Speed " + brickPi.getMotor(0).getCurrentSpeed() + " encoder " + brickPi.getMotor(0).getCurrentEncoderValue());
} catch (InterruptedException ex) {
// ignore
}
}

this code is a snap from the whole source code that’s on Github
as i said the problem is give random speed for the motor.
also the motor still working after the loop is finished for a while then stop which suppose to exit and stop when the loop end.

Thanks for your help.