Compare code of two similar java programs


Discuss the below:

Q: Compare code of 2 similar Java programs and explain differences.

First code:

// DistanceConv.java

// Java program that, given a distance in metres outputs that distance in kilometres
// rounded to the nearest whole kilometre.
// For example, given 1100m the output will be 1km, and given 1900m the output will be 2km.

import java.io.*; // java Input/Output package

public class DistanceConv // declares class DistanceConv

{
static double kilo;
static double meter;

public static void main( String[] args) // begin main method

{
InputStreamReader stdin = new InputStreamReader(System.in); // class reads characters
BufferedReader console = new BufferedReader(stdin); // class buffereing character streams
String s; // input distance

System.out.println("Please Enter the distance in meters");

try // prompt and input

{
s = console.readLine(); // reading a string
meter = Double.parseDouble(s); // parsing a double value from the string
}

catch(IOException ioex) // exeption handling

{
System.out.println("Input error"); // error output if invalid data
System.exit(1); // program terminates
}

//conversion
kilo = converToKilo(meter); //calling the function to do the job
//output
System.out.println(meter + " is equivalent to " + kilo + " kilometers");

} // end method main

private static double converToKilo(double meter) // method convert

{
double temp;
temp = meter/1000; // every 1000 meters make a kilometer
return Math.round(temp); // Math.round rounds the decimal number to the nearest integer

} // end method convert

} // end class DistanceConv

Second code:

// KilometresOutput.java
// Convert a given number of metres to the nearest kilometre

import java.util.Scanner; // program uses class Scanner to get an input
import java.lang.Math; // program also uses class Math to round a number to the nearest integer

public class KilometresOutput
{
// main method begins program execution
public static void main(String[] args)
{
// create a Scanner to obtain input from command window
Scanner input = new Scanner ( System.in );
float myMetres; // has to be a float because otherwise when it is divided the non-integer part would be stripped.
int myKilometres;

System.out.println( "\nThis program will convert a given number of metres to the nearest kilometre" );
System.out.print( "\nPlease enter the number of metres:" ); //prompt
myMetres = input.nextFloat(); // read how many metres to convert from user

myKilometres = Math.round( myMetres / 1000 ); // convert metres to kilometres and round to the nearest whole km

System.out.println( myMetres + "m to the nearest Kilometre is: " + myKilometres + "Km" ); // give user the result

} // end main
} // end class KilometreOutput

Solution Preview :

Prepared by a verified Expert
JAVA Programming: Compare code of two similar java programs
Reference No:- TGS01935670

Now Priced at $25 (50% Discount)

Recommended (98%)

Rated (4.3/5)