Expression building for Unit conversion – Computer Sir Ki Class Code Learning #JAVA#3773    ## Expression building for Unit conversion

Building of expressions can be done for different units using different divisors.

## Learning Objectives

• Making simple formulas.
• Reuse of left hand side variable for recalculation with new units in a formula.

## Source Code

 class ExpUnitConversion { public static void main(String[] args) { double d,t,s; d=1200;t=400; s=d/t; System.out.println("Speed (in m/s) = "+s); s=(d/1000)/(t/3600); System.out.println("Speed (in km/hr) = "+s); } } .linedwrap { border: 1px solid #c0c0c0; padding-top: 5px; padding-bottom: 5px; border-radius: 4px; background-color:#F8F8F8; } .linedtextarea { padding: 0px; margin: 0px; background-color:#F8F8F8; } .linedtextarea textarea, .linedwrap .codelines .lineno { font-size: 12pt; font-family: monospace; line-height: normal !important; } .linedtextarea textarea { padding-right:0.3em; padding-top:0.3em; border: 0; } .linedwrap .lines { margin-top: 0px; width: 20px; float: left; overflow: hidden; border-right: 1px solid #c0c0c0; margin-right: 10px; } .linedwrap .codelines { padding-top: 5px; } .linedwrap .codelines .lineno { color:#AAAAAA; padding-right: 2px; padding-top: 0.0em; text-align: right; white-space: nowrap; } .linedwrap .codelines .lineselect { color: red; }

## Run Output

``````Speed (in m/s) = 3.0
Speed (in km/hr) = 10.8``````

## Code Understanding

double d,t,s; //Three double variables declared
d=1200;t=400;
d assigned 1200 which is distance in meters and t assigned 400 which is time in seconds

s=d/t;
This formula will thus  give speed in m/s in variable s based on values filled in d and t variable.

System.out.println(“Speed (in m/s) = “+s);
Speed in m/s will be printed

s=(d/1000)/(t/3600);
Since the s above has already been printed for value in m/s we can again build a new formula for km/hr speed and fill its value in s. For km/hr formula we simply divide meter value in d with 1000 as 1 km=1000 m and t with 3600 as 1 hour = 3600 seconds. For this division we do it in separate brackets so that precedence of operator rules are properly followed.
System.out.println(“Speed (in km/hr) = “+s);

System.out.println(“Speed (in km/hr) = “+s);
With this we print the speed in km/hr as the s will now contain value based on recalculation based on new formula.

## Notes

• Reuse of variables should normally be done only when it is being used for similar purposes.
• Reuse of variables may be avoided if the use of variables is required for displaying all values together.

Suggested Filename(s): ExpUnitConversion.java

sunmitra| Created: 5-Mar-2018 | Updated: 5-Mar-2018|

×