You want to know how many feet are in 3.5 yards, and how many inches are in 3.5
ID: 671685 • Letter: Y
Question
You want to know how many feet are in 3.5 yards, and how many inches are in 3.5 yards. You write the following program for that purpose:
public class DistanceConverter
{
public static void main(String[] args)
{
double yards = 3.5;
double feet = yards * 3;
double inches = feet * 12;
System.out.println(yards + "yards are" + feet + "feet");
System.out.println(yards + "yards are" + inches + "inches");
}
}
The problem with the program above is that using "magic numbers" makes it hard to maintain and debug. Modify the program so that it uses constants to improve legibility and make it easier to maintain.
Explanation / Answer
public class DistanceConverter
{
private static final int YARD_TO_FEET = 3;
private static final int YARD_TO_INCH = 36;
public static void main(String[] args)
{
double yards = 3.5;
double feet = yards * YARD_TO_FEET;
double inches = yards * YARD_TO_INCH;
System.out.println(yards + "yards are" + feet + "feet");
System.out.println(yards + "yards are" + inches + "inches");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.