Distance Sensor for IQ problems in VEXcode Blocks

Trying to get a distance sensor to work with an autonomous robot (simple drivetrain.) The robot behaves erratically - either drives straight into the wall, or just starts turning. When I tried to just get the sensor to print to brain, it reports random numbers. Tried swapping out for another sensor, but same result. Components are all updated. Here is one version of the code I’ve tried (also tried a while loop):

If it’s just printing random numbers, then it’s not a problem with this piece of code. You might have an issue with something else handling Distance.

Should it be random numbers if I’m moving it closer and closer to a wall?

Is this a 1st Gen ultrasonic sensor?
If you go to Settings and the Device Info on the Brain, does the dashboard for the sensor give sensible readings?

Yes, this is a 1st generation sensor. When I go into Settings>Device Info and check the sensor readings, it gives erratic measurements.

OK, I swapped out the distance sensor yet again, and this one works better. Guess I just have some bad ones in the bunch. Also, I installed a gyro sensor, which helped with the turns. And finally, I moved the distance sensor to a higher location on the robot, because I think the jerkiness of the robot was causing the sensor to pick up the floor sometimes.