Google Answers Logo
View Question
 
Q: JAVA PROGRAMMING CODINGS ( Answered,   1 Comment )
Question  
Subject: JAVA PROGRAMMING CODINGS
Category: Computers > Programming
Asked by: aldaweesh-ga
List Price: $50.00
Posted: 24 Sep 2005 13:49 PDT
Expires: 24 Oct 2005 13:49 PDT
Question ID: 572099
Check03C (TS = 35)
We want to develop an app that converts a distance in centimeters into
the corresponding distance in miles, yards, feet and inches. Recall
that

1 mile is 1760 yards, 
1 yard is 3 feet, and 
1 yard is 36 inches 
and that 
1 centimeter is appromately 0.01094 yards. 
Analysis
The input must be prompted with the message 
  Enter the distance in centimeters

The entry is made on the next line; it consists of a nonnegative whole
number. If the entry is not a whole number, then an exception should
occur. If the entry is negative, then a runtime exception with the
message Value out of range should occur. The output consists of one
line containing, from left to right, the following elements separated
by a space: the entered number, the string cm, the equal sign, the
corresponding number of miles, the string miles,, the corresponding
number of yards, the string yards,, the corresponding number of feet,
the string feet, and, the corresponding inches rounded to two
decimals, and the string inches. Here are some sample runs of the
proposed system:
  Enter the distance in centimeters
  1234567
  1234567 cm = 7 miles, 1186 yards, 0 feet, and 5.87 inches

  Enter the distance in centimeters
  1
  1 cm = 0 miles, 0 yards, 0 feet, and 0.39 inches

  Enter the distance in centimeters
  553
  553 cm = 0 miles, 6 yards, 0 feet, and 1.79 inches

  Enter the distance in centimeters
  -5
  Exception in thread "main" java.lang.RuntimeException: Value out of range
  ....

  Enter the distance in centimeters
  2.5
  Exception in thread "main" java.util.InputMismatchException
  ...

  Enter the distance in centimeters
  a
  Exception in thread "main" java.util.InputMismatchException
  ...

Design
The tasks in our project are the following: printing on the screen,
reading from the user, validating the input, converting, formatting
and printing. The ready-made classes Scanner, PrintStream and ToolBox
contain methods for reading input, for writing and formatting output
and for input validation. This leaves the conversion issue. We can
first convert from centimeters to yards, and subsequently determine
the number of miles, yards, feet and inches.
Implementation
We leave this part to you. 
Testing
We need to test our app to establish confidence in the correctness of
our program. We supply various input cases to it, examine the output
for each, and compare it with what we deem to be the correct answer.
Here are some input cases (and the expected output):
Normal cases: 3 (little more than 1 inch), 31 (little more than 1
foot), 91 (little more than 1 yard), 161000 (little more than 1 mile);
Boundary case: 0; 
Out of range: -1, -100 (runtime exception with message Value out of range); 
Fractional: 7.5, -5.8 (exception); 
Non-numeric: one, 3a (exception); 
Develop, test and eCheck Check03C. 

Recall that eCheck defines correctness relative to the specification,
not to some subjective measure of goodness. It may consider your app
incorrect even if the "important" or "noncosmetic" part of it is
correct.
Answer  
Subject: Re: JAVA PROGRAMMING CODINGS
Answered By: leapinglizard-ga on 24 Sep 2005 16:56 PDT
 
Dear aldaweesh,

Below is a Java program, entitled Distance.java, that implements the
specifications given above. Following that is the output resulting
from the specified input cases.

Regards,

leapinglizard



//=====begin Distance.java

import java.lang.*;
import java.util.*;
import java.io.*;

public class Distance {
    public static void main(String[] argv) throws Exception {
        PrintStream out = System.out;
        BufferedReader in =
            new BufferedReader(new InputStreamReader(System.in));
        int cm;

        while (true) {              // loop breaks on empty input or exception
            out.println("Enter the distance in centimeters");
            String line = in.readLine();
            if (line == null)
                break;

            try {                   // attempt integer conversion
                cm = new Integer(line).intValue();
            } catch (NumberFormatException e) {
                throw new InputMismatchException();
            }

            if (cm < 0)             // exception for negative value
                throw new RuntimeException("Value out of range");

                                    // convert to inches as per specification
            double inches_double = cm * 0.01094 * 36;
            int inches = (int) inches_double;
            int miles = inches / (1760 * 36);
            inches -= 1760 * 36 * miles;
            int yards = inches / 36;
            inches -= 36 * yards;
            int feet = inches / 12;
            inches -= 12 * feet;
                                    // compute first two decimal digits
            double decimal = inches_double - (double) ((int) inches_double);
            int decimal_int = (int) Math.round(100 * decimal);
            int tens = decimal_int / 10;
            int ones = decimal_int % 10;

            out.print(cm+" cm = "); // print results as specified
            out.print(miles+" miles, ");
            out.print(yards+" yards, ");
            out.print(feet+" feet, and ");
            out.print(inches+"."+tens+ones+" inches\n\n");
        }
    }
}

//=====end Distance.java



$ java Distance 
Enter the distance in centimeters
3
3 cm = 0 miles, 0 yards, 0 feet, and 1.18 inches

Enter the distance in centimeters
31
31 cm = 0 miles, 0 yards, 1 feet, and 0.21 inches

Enter the distance in centimeters
91
91 cm = 0 miles, 0 yards, 2 feet, and 11.84 inches

Enter the distance in centimeters
161000
161000 cm = 1 miles, 1 yards, 1 feet, and 0.24 inches

Enter the distance in centimeters
0
0 cm = 0 miles, 0 yards, 0 feet, and 0.00 inches

Enter the distance in centimeters
-1
Exception in thread "main" java.lang.RuntimeException: Value out of range
        at Distance.main(Distance.java:27)

$ java Distance 
Enter the distance in centimeters
-100
Exception in thread "main" java.lang.RuntimeException: Value out of range
        at Distance.main(Distance.java:27)

$ java Distance 
Enter the distance in centimeters
7.5
Exception in thread "main" java.util.InputMismatchException
        at Distance.main(Distance.java:23)

$ java Distance 
Enter the distance in centimeters
-5.8
Exception in thread "main" java.util.InputMismatchException
        at Distance.main(Distance.java:23)

$ java Distance 
Enter the distance in centimeters
one
Exception in thread "main" java.util.InputMismatchException
        at Distance.main(Distance.java:23)

$ java Distance 
Enter the distance in centimeters
3a
Exception in thread "main" java.util.InputMismatchException
        at Distance.main(Distance.java:23)

Request for Answer Clarification by aldaweesh-ga on 30 Sep 2005 01:27 PDT
please don't use the while loop command .
please use Scanner instead of BufferedReader.

Clarification of Answer by leapinglizard-ga on 30 Sep 2005 05:28 PDT
You will find a new version below. There is no loop in this one, so it
prompts for input only once. I have also replaced the BufferedReader
instance with a Scanner.

leapinglizard


//=====begin Distance.java

import java.lang.*;
import java.util.*;
import java.io.*;

public class Distance {
    public static void main(String[] argv) throws Exception {
        PrintStream out = System.out;
        Scanner in = new Scanner(System.in);
        int cm;

        out.println("Enter the distance in centimeters");
        String line = in.nextLine();

        try {                   // attempt integer conversion
            cm = new Integer(line).intValue();
        } catch (NumberFormatException e) {
            throw new InputMismatchException();
        }

        if (cm < 0)             // exception for negative value
            throw new RuntimeException("Value out of range");

                                // convert to inches as per specification
        double inches_double = cm * 0.01094 * 36;
        int inches = (int) inches_double;
        int miles = inches / (1760 * 36);
        inches -= 1760 * 36 * miles;
        int yards = inches / 36;
        inches -= 36 * yards;
        int feet = inches / 12;
        inches -= 12 * feet;
                                // compute first two decimal digits
        double decimal = inches_double - (double) ((int) inches_double);
        int decimal_int = (int) Math.round(100 * decimal);
        int tens = decimal_int / 10;
        int ones = decimal_int % 10;

        out.print(cm+" cm = "); // print results as specified
        out.print(miles+" miles, ");
        out.print(yards+" yards, ");
        out.print(feet+" feet, and ");
        out.print(inches+"."+tens+ones+" inches\n");
    }
}

//=====end Distance.java
Comments  
Subject: Re: JAVA PROGRAMMING CODINGS
From: franck_van_breugel-ga on 09 Oct 2005 14:24 PDT
 
It is dubious whether homework questions should be posted on
Google answers (cf. http://www.cs.yorku.ca/~franck/teaching/2005-06/1020/eCheck/Check03C.html).
Handing in an answer found on Google answers (without
properly acknowledging the source) is academically dishonest
(cf. http://www.cs.yorku.ca/admin/coscOnAcadHonesty.html). 

Now let us have a look at the posted answer.  The fragment

  int cm;

  out.println("Enter the distance in centimeters");
  String line = in.nextLine();

  try {                   // attempt integer conversion
      cm = new Integer(line).intValue();
  } catch (NumberFormatException e) {
      throw new InputMismatchException();
  }

can be simplified to

  out.println("Enter the distance in centimeters");
  int cm = in.nextInt();

Simpler code is preferable as it is easier to read, maintain, etc.

The code contains many magic numbers (numbers different from
0, 1, -1, 2, and -2).  It is better to introduce constants like

  final double YARDS_PER_CENTIMETER = 0.01094;
  final int YARDS_PER_MILE = 1760;
  final int FEET_PER_YARD = 3;
  final int INCHES_PER_YARD = 3 * 12;

This improves the readability of the code and also makes it easier
to maintain.

Some spaces may be added to

  out.print(inches+"."+tens+ones+" inches\n");

to improve the readability.  For example,

  out.println(inches + "." + tens + ones + " inches");

follows the coding style conventions that are advocated in the
textbook "Java by Abstraction."

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy