I believe you know this formula of sound v = 2x/t .
It's used to find
- v which is speed of the sound in meters per second m/s.
- x which is the distance of the sound in meters m,
- t which is time in seconds s/
/*
* This class just construct the formulae for solving
* speed of sound
* distance of sounde
* and time sound take to reach back it's
* Notice that the class doesn't contain a main method
*/
public class Sound
{
// Inatialise our varibles
public double v;
public double x;
public double t;
// method for calculating speed of sound
public double speed(double x, double t)
{
v = (2*x)/t;
return v;
}
// method for calculatin distance of sound
public double distance(double v, double t)
{
x =(v*t)/2;
return x;
}
// method for calculating time
public double time(double v, double x)
{
t = (2*x)/v;
return t;
}
}
Next, we create the file SoundDrive.java which will contain the main method. You must also save the two files(i.e Sound.java and SoundDrive,java) in the same directory.
In the SoundDrive.java you will notice how we create and object calc using our Sound class, after creating the object we are able to access it;s methods and variables.
Below is the Source code for the SoundDrive.java
import java.util.Scanner;
public class SoundDrive
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); // construct input
Sound calc = new Sound(); //create obkect of class sound
String get;
System.out.println("This program calculate Speed of sound, distance of the"
+ " sound and the time sound take to echo.\n How to work with it, enter "
+ "v to calculate sound speed, enter x to calculate distance of sound\n or enter t"
+ " to calculate time.");
System.out.print("Enter V, X or T or enter any key to exit: "); // prompt user for selection
get = input.nextLine(); //
if (get.equalsIgnoreCase("v"))
{
System.out.print("Enter Distance: ");
double dst,tm;
dst = input.nextDouble();
System.out.print("Enter Time: ");
tm = input.nextDouble();
System.out.println("The speed of sound = "+calc.speed(dst, tm)+"m/s");
}
else if (get.equalsIgnoreCase("x"))
{
System.out.print("Enter Speed: ");
double spd,tm;
spd = input.nextDouble();
System.out.print("Enter Time: ");
tm = input.nextDouble();
System.out.println("The distance X = "+calc.distance(spd, tm)+"m");
}
else if (get.equalsIgnoreCase("t"))
{
System.out.print("Enter Speed: ");
double spd,dst;
spd = input.nextDouble();
System.out.print("Enter Distance: ");
dst = input.nextDouble();
System.out.println("The time T = " +calc.distance(spd, dst)+"s");
}
}
}
This is small example about the concept of OOP in java. Have fun with it.
No comments:
Post a Comment