I have to make a program that lets a user select between 4 options and then choose a distance of their choosing. It's trying to figure out how fast sound travels through certain objects. I have to have a demo program and a separate class.
As you will see I have a lot of repeating calculations. I'm just not sure what needs to be where, and I am not sure of what the output statement should be.
public class Sound { private final double air = 1100; private final double water = 4900; private final double steel = 16400; double distance; double time; // no arg constructor public Sound() { distance = 0.0; } //parameterized constructor public Sound(double d) { distance = d; } //mutator methods public void setDistance(double d) { distance = d; } //accessor methods public double getSpeedInAir() { return distance / 1100; } public double getSpeedInWater() { return distance / 4900; } public double getSpeedInSteel() { return distance / 16400; } }
import java.util.Scanner; import java.text.DecimalFormat; public class SoundDemo { public static void main(String[] args) { double choice; double time; double distance; Scanner keyboard = new Scanner(System.in); System.out.print("Please choose 1. Air 2. Water 3. Steel 4. Quit "); choice = keyboard.nextDouble(); System.out.print("What distance would you like to know? "); distance = keyboard.nextDouble(); if (choice.equals("1")) { time = (distance / 1100); System.out.println("The total time traveled is " + time + "."); } else if (choice.equals("2")) { time = (distance / 4900); System.out.println("The total time traveled is " + time + "."); } else if (choice.equals("3")) { time = (distance / 16400); System.out.println("The total time traveled is " + time + "."); } else if (choice.equals(" ")) { System.out.println("Invalid input!"); } } }
Comment