I've been working on learning Java and this was a challenge as part of a chapter on data types:
Create a program that computes how far away, in feet, a listener is from a sound. Sound travels approximately 1,100 feet per second through air.
You can also compute the distance to a large object, such as a rock wall, by timing the echo. For example, if you clap your hands and time how long it takes for you to hear the echo, then you know the total round-trip time.
Java: A Beginner's Guide, Sixth Edition - by Herbert Schildt · McGraw-Hill Education (Chapter 2)
I'm super-new to OOP and am trying to nip bad habits in the bud, so-to-speak. I've divided the logic in one class as much as I think is possible (at my current skill level).
SoundSpeed.java
public class SoundSpeed {
private final double SOUND_TRAVEL_SPEED = 1100;
public double timeInSeconds;
public boolean isEcho;
private int distanceDivisor;
double getResult() {
if(isEcho) {
distanceDivisor = 2;
} else {
distanceDivisor = 1;
}
return (timeInSeconds * SOUND_TRAVEL_SPEED) / distanceDivisor;
}
}
SoundSpeedCalc.java
class SoundSpeedCalc {
public static void main(String args[]) {
SoundSpeed soundSpeed = new SoundSpeed();
soundSpeed.timeInSeconds = 35.079;
soundSpeed.isEcho = true;
String verb;
if(soundSpeed.isEcho) {
verb = "echo";
} else {
verb = "travel";
}
System.out.println("The sound took " + soundSpeed.timeInSeconds + " seconds to "
+ verb + " and thus the distance is " + soundSpeed.getResult() + " feet away.");
}
}
Example output (using above parameters in main
):
The sound took 35.079 seconds to echo and thus the distance is 19293.45 feet away.
Example output if I set soundSpeed.isEcho
to false
:
The sound took 35.079 seconds to travel and thus the distance is 38586.9 feet away.