SlideShare a Scribd company logo
1 of 16
Download to read offline
package length;
/**
* A Length is an object that has a length and a unit, can be converted to
* meters, can be added to other Lengths, and can be compared to other Lengths.
*
* @author Tom Bylander
*/
publicabstractclass Length implements Comparable {
/**
* The length in the units of this object.
*/
privatedouble length;
/**
* Store the length in this Length.
*
* @param length
*/
public Length(double length) {
this.length = length;
}
/**
* This should add the other Length to this Length object.
*
* @param other
*/
publicabstractvoid add(Length other);
/**
* This should return a different String if the length is exactly 1.0.
*
* @return the correct name of the unit of this Length object.
*/
publicabstract String getUnit();
/**
* @return the length in meters
*/
publicabstractdouble toMeters();
/**
* @return the length of this Length object.
*/
publicdouble getLength() {
return length;
}
/**
* Set the length of this Length object.
*
* @param length
* length in the units of this object
*/
publicvoid setLength(double length) {
this.length = length;
}
/**
* Compare this Length object to the other one.
*/
publicint compareTo(Length other) {
if((this.toMeters() - other.toMeters()) < 0)
return -1;
elseif((this.toMeters() - other.toMeters()) > 0)
return 1;
return 0;
}
/**
* @return a String that includes the class name, the length, and the unit.
*/
public String toString() {
returnthis.getClass() + ": " + getLength() + " " + getUnit();
}
}
package length;
publicclass Meter extends Length{
/**
* Parameterized constructor
* @param length
*/
public Meter(double length) {
super(length);
}
@Override
publicvoid add(Length other) {
setLength(other.toMeters() + getLength());
}
@Override
public String getUnit() {
if(getLength() == 1.0)
return "meter";
else
return "meters";
}
@Override
publicdouble toMeters() {
return getLength();
}
}
package length;
publicclass Inch extends Length {
/**
* 1 inch = 0.0254 meters
*/
publicstaticfinaldoubleMETERS_PER_INCH = 0.0254;
/**
* Parameterized constructor
* @param length
*/
public Inch(double length) {
super(length);
}
@Override
publicvoid add(Length other) {
double otherToInch = other.toMeters() / METERS_PER_INCH;
setLength(otherToInch + getLength());
}
@Override
public String getUnit() {
if(getLength() == 1.0)
return "inch";
else
return "inches";
}
@Override
publicdouble toMeters() {
return (getLength() * METERS_PER_INCH);
}
}
package length;
publicclass Foot extends Length {
/**
* 1 foot = 0.3048 meters
*/
publicstaticfinaldoubleMETERS_PER_FOOT = 0.3048;
/**
* Parameterized constructor
* @param length
*/
public Foot(double length) {
super(length);
}
@Override
publicvoid add(Length other) {
double otherToFoot = other.toMeters() / METERS_PER_FOOT;
setLength(otherToFoot + getLength());
}
@Override
public String getUnit() {
if(getLength() == 1.0)
return "foot";
else
return "feet";
}
@Override
publicdouble toMeters() {
return (getLength() * METERS_PER_FOOT);
}
}
package length;
publicclass Yard extends Length{
/**
* 1 yard = 0.9144 meters
*/
publicstaticfinaldoubleMETERS_PER_YARD = 0.9144;
/**
* Parameterized constructor
* @param length
*/
public Yard(double length) {
super(length);
}
@Override
publicvoid add(Length other) {
double otherToYard = other.toMeters() / METERS_PER_YARD;
setLength(otherToYard + getLength());
}
@Override
public String getUnit() {
if(getLength() == 1.0)
return "yard";
else
return "yards";
}
@Override
publicdouble toMeters() {
return (getLength() * METERS_PER_YARD);
}
}
package length;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
publicclass LengthTest {
publicstaticvoid main(String[] args) {
Scanner in = null;
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
thrownew RuntimeException("failed to open data.txt");
}
//ArrayList to hold Length objects
List lengthList = new ArrayList();
while (in.hasNextDouble()) {
double value = in.nextDouble();
String unit = in.next();
Length length = null;
//Create the right type of Length object and store it in length
if(unit.equalsIgnoreCase("meter") || unit.equalsIgnoreCase("meters"))
length = new Meter(value);
elseif(unit.equalsIgnoreCase("inch") || unit.equalsIgnoreCase("inches"))
length = new Inch(value);
elseif(unit.equalsIgnoreCase("foot") || unit.equalsIgnoreCase("feet"))
length = new Foot(value);
elseif(unit.equalsIgnoreCase("yard") || unit.equalsIgnoreCase("yards"))
length = new Yard(value);
System.out.println(length);
//Add length to arraylist
lengthList.add(length);
}
// Close scanner object
in.close();
//Display minimum and maximum length
Collections.sort(lengthList);
System.out.println(" Minimum is " + lengthList.get(0));
System.out.println("Maximum is " + lengthList.get(lengthList.size() - 1));
//Sum of Lengths Adding from First to Last
Meter meter = new Meter(0);
Inch inch = new Inch(0);
Foot foot = new Foot(0);
Yard yard = new Yard(0);
for (Length length : lengthList) {
meter.add(length);
inch.add(length);
foot.add(length);
yard.add(length);
}
System.out.println(" Sum of Lengths Adding from First to Last");
System.out.println(meter);
System.out.println(inch);
System.out.println(foot);
System.out.println(yard);
//Sum of Lengths Adding from Last to First
System.out.println(" Sum of Lengths Adding from Last to First");
meter = new Meter(0);
inch = new Inch(0);
foot = new Foot(0);
yard = new Yard(0);
//Reverse list to calculate sum from last to first
Collections.reverse(lengthList);
for (Length length : lengthList) {
meter.add(length);
inch.add(length);
foot.add(length);
yard.add(length);
}
System.out.println(meter);
System.out.println(inch);
System.out.println(foot);
System.out.println(yard);
}
}
SAMPLE OUTPUT:
class length.Meter: 1.0 meter
class length.Inch: 1.0 inch
class length.Foot: 1.0 foot
class length.Yard: 1.0 yard
class length.Meter: 401.336 meters
class length.Inch: 15839.0 inches
class length.Foot: 1319.0 feet
class length.Yard: 439.0 yards
Minimum is class length.Inch: 1.0 inch
Maximum is class length.Inch: 15839.0 inches
Sum of Lengths Adding from First to Last
class length.Meter: 1609.344 meters
class length.Inch: 63360.00000000001 inches
class length.Foot: 5280.0 feet
class length.Yard: 1760.0 yards
Sum of Lengths Adding from Last to First
class length.Meter: 1609.3439999999996 meters
class length.Inch: 63360.0 inches
class length.Foot: 5279.999999999999 feet
class length.Yard: 1760.0 yards
Solution
package length;
/**
* A Length is an object that has a length and a unit, can be converted to
* meters, can be added to other Lengths, and can be compared to other Lengths.
*
* @author Tom Bylander
*/
publicabstractclass Length implements Comparable {
/**
* The length in the units of this object.
*/
privatedouble length;
/**
* Store the length in this Length.
*
* @param length
*/
public Length(double length) {
this.length = length;
}
/**
* This should add the other Length to this Length object.
*
* @param other
*/
publicabstractvoid add(Length other);
/**
* This should return a different String if the length is exactly 1.0.
*
* @return the correct name of the unit of this Length object.
*/
publicabstract String getUnit();
/**
* @return the length in meters
*/
publicabstractdouble toMeters();
/**
* @return the length of this Length object.
*/
publicdouble getLength() {
return length;
}
/**
* Set the length of this Length object.
*
* @param length
* length in the units of this object
*/
publicvoid setLength(double length) {
this.length = length;
}
/**
* Compare this Length object to the other one.
*/
publicint compareTo(Length other) {
if((this.toMeters() - other.toMeters()) < 0)
return -1;
elseif((this.toMeters() - other.toMeters()) > 0)
return 1;
return 0;
}
/**
* @return a String that includes the class name, the length, and the unit.
*/
public String toString() {
returnthis.getClass() + ": " + getLength() + " " + getUnit();
}
}
package length;
publicclass Meter extends Length{
/**
* Parameterized constructor
* @param length
*/
public Meter(double length) {
super(length);
}
@Override
publicvoid add(Length other) {
setLength(other.toMeters() + getLength());
}
@Override
public String getUnit() {
if(getLength() == 1.0)
return "meter";
else
return "meters";
}
@Override
publicdouble toMeters() {
return getLength();
}
}
package length;
publicclass Inch extends Length {
/**
* 1 inch = 0.0254 meters
*/
publicstaticfinaldoubleMETERS_PER_INCH = 0.0254;
/**
* Parameterized constructor
* @param length
*/
public Inch(double length) {
super(length);
}
@Override
publicvoid add(Length other) {
double otherToInch = other.toMeters() / METERS_PER_INCH;
setLength(otherToInch + getLength());
}
@Override
public String getUnit() {
if(getLength() == 1.0)
return "inch";
else
return "inches";
}
@Override
publicdouble toMeters() {
return (getLength() * METERS_PER_INCH);
}
}
package length;
publicclass Foot extends Length {
/**
* 1 foot = 0.3048 meters
*/
publicstaticfinaldoubleMETERS_PER_FOOT = 0.3048;
/**
* Parameterized constructor
* @param length
*/
public Foot(double length) {
super(length);
}
@Override
publicvoid add(Length other) {
double otherToFoot = other.toMeters() / METERS_PER_FOOT;
setLength(otherToFoot + getLength());
}
@Override
public String getUnit() {
if(getLength() == 1.0)
return "foot";
else
return "feet";
}
@Override
publicdouble toMeters() {
return (getLength() * METERS_PER_FOOT);
}
}
package length;
publicclass Yard extends Length{
/**
* 1 yard = 0.9144 meters
*/
publicstaticfinaldoubleMETERS_PER_YARD = 0.9144;
/**
* Parameterized constructor
* @param length
*/
public Yard(double length) {
super(length);
}
@Override
publicvoid add(Length other) {
double otherToYard = other.toMeters() / METERS_PER_YARD;
setLength(otherToYard + getLength());
}
@Override
public String getUnit() {
if(getLength() == 1.0)
return "yard";
else
return "yards";
}
@Override
publicdouble toMeters() {
return (getLength() * METERS_PER_YARD);
}
}
package length;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
publicclass LengthTest {
publicstaticvoid main(String[] args) {
Scanner in = null;
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
thrownew RuntimeException("failed to open data.txt");
}
//ArrayList to hold Length objects
List lengthList = new ArrayList();
while (in.hasNextDouble()) {
double value = in.nextDouble();
String unit = in.next();
Length length = null;
//Create the right type of Length object and store it in length
if(unit.equalsIgnoreCase("meter") || unit.equalsIgnoreCase("meters"))
length = new Meter(value);
elseif(unit.equalsIgnoreCase("inch") || unit.equalsIgnoreCase("inches"))
length = new Inch(value);
elseif(unit.equalsIgnoreCase("foot") || unit.equalsIgnoreCase("feet"))
length = new Foot(value);
elseif(unit.equalsIgnoreCase("yard") || unit.equalsIgnoreCase("yards"))
length = new Yard(value);
System.out.println(length);
//Add length to arraylist
lengthList.add(length);
}
// Close scanner object
in.close();
//Display minimum and maximum length
Collections.sort(lengthList);
System.out.println(" Minimum is " + lengthList.get(0));
System.out.println("Maximum is " + lengthList.get(lengthList.size() - 1));
//Sum of Lengths Adding from First to Last
Meter meter = new Meter(0);
Inch inch = new Inch(0);
Foot foot = new Foot(0);
Yard yard = new Yard(0);
for (Length length : lengthList) {
meter.add(length);
inch.add(length);
foot.add(length);
yard.add(length);
}
System.out.println(" Sum of Lengths Adding from First to Last");
System.out.println(meter);
System.out.println(inch);
System.out.println(foot);
System.out.println(yard);
//Sum of Lengths Adding from Last to First
System.out.println(" Sum of Lengths Adding from Last to First");
meter = new Meter(0);
inch = new Inch(0);
foot = new Foot(0);
yard = new Yard(0);
//Reverse list to calculate sum from last to first
Collections.reverse(lengthList);
for (Length length : lengthList) {
meter.add(length);
inch.add(length);
foot.add(length);
yard.add(length);
}
System.out.println(meter);
System.out.println(inch);
System.out.println(foot);
System.out.println(yard);
}
}
SAMPLE OUTPUT:
class length.Meter: 1.0 meter
class length.Inch: 1.0 inch
class length.Foot: 1.0 foot
class length.Yard: 1.0 yard
class length.Meter: 401.336 meters
class length.Inch: 15839.0 inches
class length.Foot: 1319.0 feet
class length.Yard: 439.0 yards
Minimum is class length.Inch: 1.0 inch
Maximum is class length.Inch: 15839.0 inches
Sum of Lengths Adding from First to Last
class length.Meter: 1609.344 meters
class length.Inch: 63360.00000000001 inches
class length.Foot: 5280.0 feet
class length.Yard: 1760.0 yards
Sum of Lengths Adding from Last to First
class length.Meter: 1609.3439999999996 meters
class length.Inch: 63360.0 inches
class length.Foot: 5279.999999999999 feet
class length.Yard: 1760.0 yards

More Related Content

Similar to package length; A Length is an object that has a length and .pdf

2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfaromanets
 
public class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfpublic class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfarjuncp10
 
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdfCopy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdffacevenky
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methodsphil_nash
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfarpaqindia
 
Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced Flink Forward
 
Adapt your code from Assignment 2 to use both a Java API ArrayList a.pdf
Adapt your code from Assignment 2 to use both a Java API ArrayList a.pdfAdapt your code from Assignment 2 to use both a Java API ArrayList a.pdf
Adapt your code from Assignment 2 to use both a Java API ArrayList a.pdfalbarefqc
 
Introduction à Dart
Introduction à DartIntroduction à Dart
Introduction à DartSOAT
 
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdf
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdfpublic static ArrayListInteger doArrayListInsertAtMedian(int nu.pdf
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdfarihanthtoysandgifts
 
in c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdfin c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdfstopgolook
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeDaniel Wellman
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesNebojša Vukšić
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.Russell Childs
 
[SpLab3]Structures
[SpLab3]Structures[SpLab3]Structures
[SpLab3]StructuresNora Youssef
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java Sorting CodeImplementing and testing all three sort algorithm.pdf
Java Sorting CodeImplementing and testing all three sort algorithm.pdfJava Sorting CodeImplementing and testing all three sort algorithm.pdf
Java Sorting CodeImplementing and testing all three sort algorithm.pdfforecastfashions
 
Can someoen help me to write c++ program including C++ inheritance, .pdf
Can someoen help me to write c++ program including C++ inheritance, .pdfCan someoen help me to write c++ program including C++ inheritance, .pdf
Can someoen help me to write c++ program including C++ inheritance, .pdfarrowvisionoptics
 
include ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfinclude ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfnaslin841216
 

Similar to package length; A Length is an object that has a length and .pdf (20)

2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
public class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdfpublic class Person { private String name; private int age;.pdf
public class Person { private String name; private int age;.pdf
 
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdfCopy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methods
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
 
Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced
 
Adapt your code from Assignment 2 to use both a Java API ArrayList a.pdf
Adapt your code from Assignment 2 to use both a Java API ArrayList a.pdfAdapt your code from Assignment 2 to use both a Java API ArrayList a.pdf
Adapt your code from Assignment 2 to use both a Java API ArrayList a.pdf
 
Introduction à Dart
Introduction à DartIntroduction à Dart
Introduction à Dart
 
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdf
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdfpublic static ArrayListInteger doArrayListInsertAtMedian(int nu.pdf
public static ArrayListInteger doArrayListInsertAtMedian(int nu.pdf
 
in c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdfin c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdf
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
[SpLab3]Structures
[SpLab3]Structures[SpLab3]Structures
[SpLab3]Structures
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Creating Interface- Practice Program 6.docx
Creating Interface- Practice Program 6.docxCreating Interface- Practice Program 6.docx
Creating Interface- Practice Program 6.docx
 
Java Sorting CodeImplementing and testing all three sort algorithm.pdf
Java Sorting CodeImplementing and testing all three sort algorithm.pdfJava Sorting CodeImplementing and testing all three sort algorithm.pdf
Java Sorting CodeImplementing and testing all three sort algorithm.pdf
 
Can someoen help me to write c++ program including C++ inheritance, .pdf
Can someoen help me to write c++ program including C++ inheritance, .pdfCan someoen help me to write c++ program including C++ inheritance, .pdf
Can someoen help me to write c++ program including C++ inheritance, .pdf
 
include ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdfinclude ltfunctionalgt include ltiteratorgt inclu.pdf
include ltfunctionalgt include ltiteratorgt inclu.pdf
 

More from anupamselection

1. D2. A3. D4.DSolution1. D2. A3. D4.D.pdf
1. D2. A3. D4.DSolution1. D2. A3. D4.D.pdf1. D2. A3. D4.DSolution1. D2. A3. D4.D.pdf
1. D2. A3. D4.DSolution1. D2. A3. D4.D.pdfanupamselection
 
1) pH is alkalotic and it is caused due to combined (mixed) alkalosi.pdf
1) pH is alkalotic and it is caused due to combined (mixed) alkalosi.pdf1) pH is alkalotic and it is caused due to combined (mixed) alkalosi.pdf
1) pH is alkalotic and it is caused due to combined (mixed) alkalosi.pdfanupamselection
 
1) Economical for transport of goods and services2) Reducing traff.pdf
1) Economical for transport of goods and services2) Reducing traff.pdf1) Economical for transport of goods and services2) Reducing traff.pdf
1) Economical for transport of goods and services2) Reducing traff.pdfanupamselection
 
There are some general processes which you need to follow while crea.pdf
There are some general processes which you need to follow while crea.pdfThere are some general processes which you need to follow while crea.pdf
There are some general processes which you need to follow while crea.pdfanupamselection
 
All of the above.Solution All of the above..pdf
 All of the above.Solution All of the above..pdf All of the above.Solution All of the above..pdf
All of the above.Solution All of the above..pdfanupamselection
 
Ques-1A keystone species is defined as a species, which has an ex.pdf
Ques-1A keystone species is defined as a species, which has an ex.pdfQues-1A keystone species is defined as a species, which has an ex.pdf
Ques-1A keystone species is defined as a species, which has an ex.pdfanupamselection
 
PO42- is produced when CaPO4 is dissolved. Adding acid to the soluti.pdf
PO42- is produced when CaPO4 is dissolved. Adding acid to the soluti.pdfPO42- is produced when CaPO4 is dissolved. Adding acid to the soluti.pdf
PO42- is produced when CaPO4 is dissolved. Adding acid to the soluti.pdfanupamselection
 
picture(figure) is not clearSolutionpicture(figure) is not cle.pdf
picture(figure) is not clearSolutionpicture(figure) is not cle.pdfpicture(figure) is not clearSolutionpicture(figure) is not cle.pdf
picture(figure) is not clearSolutionpicture(figure) is not cle.pdfanupamselection
 
Name used on OSIName Used in TCPIP networksLayer 1(Physical)L.pdf
Name used on OSIName Used in TCPIP networksLayer 1(Physical)L.pdfName used on OSIName Used in TCPIP networksLayer 1(Physical)L.pdf
Name used on OSIName Used in TCPIP networksLayer 1(Physical)L.pdfanupamselection
 
Monthly interest rate=1212=1Present value(PV) of monthly payment.pdf
Monthly interest rate=1212=1Present value(PV) of monthly payment.pdfMonthly interest rate=1212=1Present value(PV) of monthly payment.pdf
Monthly interest rate=1212=1Present value(PV) of monthly payment.pdfanupamselection
 
Lab1.javaimport java.util.Scanner;package public class Lab1 .pdf
Lab1.javaimport java.util.Scanner;package public class Lab1 .pdfLab1.javaimport java.util.Scanner;package public class Lab1 .pdf
Lab1.javaimport java.util.Scanner;package public class Lab1 .pdfanupamselection
 
Interest coverage=EBITinterest expensewhich is equal to=(40020.pdf
Interest coverage=EBITinterest expensewhich is equal to=(40020.pdfInterest coverage=EBITinterest expensewhich is equal to=(40020.pdf
Interest coverage=EBITinterest expensewhich is equal to=(40020.pdfanupamselection
 
In this module, you will learn some basics about operating in Object.pdf
In this module, you will learn some basics about operating in Object.pdfIn this module, you will learn some basics about operating in Object.pdf
In this module, you will learn some basics about operating in Object.pdfanupamselection
 
When comparing the R groups of these to amino aci.pdf
                     When comparing the R groups of these to amino aci.pdf                     When comparing the R groups of these to amino aci.pdf
When comparing the R groups of these to amino aci.pdfanupamselection
 
Malonic Acid Water Soluble Methyl Alcohol Solu.pdf
                     Malonic Acid  Water Soluble Methyl Alcohol Solu.pdf                     Malonic Acid  Water Soluble Methyl Alcohol Solu.pdf
Malonic Acid Water Soluble Methyl Alcohol Solu.pdfanupamselection
 
It is true that ionization energy is required to .pdf
                     It is true that ionization energy is required to .pdf                     It is true that ionization energy is required to .pdf
It is true that ionization energy is required to .pdfanupamselection
 
Ionic compounds form when the electronegativity d.pdf
                     Ionic compounds form when the electronegativity d.pdf                     Ionic compounds form when the electronegativity d.pdf
Ionic compounds form when the electronegativity d.pdfanupamselection
 
If R is reflexive, then xRy means yRx; but then, .pdf
                     If R is reflexive, then xRy means yRx; but then, .pdf                     If R is reflexive, then xRy means yRx; but then, .pdf
If R is reflexive, then xRy means yRx; but then, .pdfanupamselection
 
H2O HBr H2 due to hydrogen bonding and then .pdf
                     H2O  HBr  H2  due to hydrogen bonding and then .pdf                     H2O  HBr  H2  due to hydrogen bonding and then .pdf
H2O HBr H2 due to hydrogen bonding and then .pdfanupamselection
 

More from anupamselection (20)

1. D2. A3. D4.DSolution1. D2. A3. D4.D.pdf
1. D2. A3. D4.DSolution1. D2. A3. D4.D.pdf1. D2. A3. D4.DSolution1. D2. A3. D4.D.pdf
1. D2. A3. D4.DSolution1. D2. A3. D4.D.pdf
 
1) pH is alkalotic and it is caused due to combined (mixed) alkalosi.pdf
1) pH is alkalotic and it is caused due to combined (mixed) alkalosi.pdf1) pH is alkalotic and it is caused due to combined (mixed) alkalosi.pdf
1) pH is alkalotic and it is caused due to combined (mixed) alkalosi.pdf
 
1) Economical for transport of goods and services2) Reducing traff.pdf
1) Economical for transport of goods and services2) Reducing traff.pdf1) Economical for transport of goods and services2) Reducing traff.pdf
1) Economical for transport of goods and services2) Reducing traff.pdf
 
There are some general processes which you need to follow while crea.pdf
There are some general processes which you need to follow while crea.pdfThere are some general processes which you need to follow while crea.pdf
There are some general processes which you need to follow while crea.pdf
 
All of the above.Solution All of the above..pdf
 All of the above.Solution All of the above..pdf All of the above.Solution All of the above..pdf
All of the above.Solution All of the above..pdf
 
Ques-1A keystone species is defined as a species, which has an ex.pdf
Ques-1A keystone species is defined as a species, which has an ex.pdfQues-1A keystone species is defined as a species, which has an ex.pdf
Ques-1A keystone species is defined as a species, which has an ex.pdf
 
PO42- is produced when CaPO4 is dissolved. Adding acid to the soluti.pdf
PO42- is produced when CaPO4 is dissolved. Adding acid to the soluti.pdfPO42- is produced when CaPO4 is dissolved. Adding acid to the soluti.pdf
PO42- is produced when CaPO4 is dissolved. Adding acid to the soluti.pdf
 
picture(figure) is not clearSolutionpicture(figure) is not cle.pdf
picture(figure) is not clearSolutionpicture(figure) is not cle.pdfpicture(figure) is not clearSolutionpicture(figure) is not cle.pdf
picture(figure) is not clearSolutionpicture(figure) is not cle.pdf
 
Name used on OSIName Used in TCPIP networksLayer 1(Physical)L.pdf
Name used on OSIName Used in TCPIP networksLayer 1(Physical)L.pdfName used on OSIName Used in TCPIP networksLayer 1(Physical)L.pdf
Name used on OSIName Used in TCPIP networksLayer 1(Physical)L.pdf
 
Monthly interest rate=1212=1Present value(PV) of monthly payment.pdf
Monthly interest rate=1212=1Present value(PV) of monthly payment.pdfMonthly interest rate=1212=1Present value(PV) of monthly payment.pdf
Monthly interest rate=1212=1Present value(PV) of monthly payment.pdf
 
Lab1.javaimport java.util.Scanner;package public class Lab1 .pdf
Lab1.javaimport java.util.Scanner;package public class Lab1 .pdfLab1.javaimport java.util.Scanner;package public class Lab1 .pdf
Lab1.javaimport java.util.Scanner;package public class Lab1 .pdf
 
Interest coverage=EBITinterest expensewhich is equal to=(40020.pdf
Interest coverage=EBITinterest expensewhich is equal to=(40020.pdfInterest coverage=EBITinterest expensewhich is equal to=(40020.pdf
Interest coverage=EBITinterest expensewhich is equal to=(40020.pdf
 
In this module, you will learn some basics about operating in Object.pdf
In this module, you will learn some basics about operating in Object.pdfIn this module, you will learn some basics about operating in Object.pdf
In this module, you will learn some basics about operating in Object.pdf
 
y = 12 x=0 z=0 .pdf
                     y = 12 x=0 z=0                                  .pdf                     y = 12 x=0 z=0                                  .pdf
y = 12 x=0 z=0 .pdf
 
When comparing the R groups of these to amino aci.pdf
                     When comparing the R groups of these to amino aci.pdf                     When comparing the R groups of these to amino aci.pdf
When comparing the R groups of these to amino aci.pdf
 
Malonic Acid Water Soluble Methyl Alcohol Solu.pdf
                     Malonic Acid  Water Soluble Methyl Alcohol Solu.pdf                     Malonic Acid  Water Soluble Methyl Alcohol Solu.pdf
Malonic Acid Water Soluble Methyl Alcohol Solu.pdf
 
It is true that ionization energy is required to .pdf
                     It is true that ionization energy is required to .pdf                     It is true that ionization energy is required to .pdf
It is true that ionization energy is required to .pdf
 
Ionic compounds form when the electronegativity d.pdf
                     Ionic compounds form when the electronegativity d.pdf                     Ionic compounds form when the electronegativity d.pdf
Ionic compounds form when the electronegativity d.pdf
 
If R is reflexive, then xRy means yRx; but then, .pdf
                     If R is reflexive, then xRy means yRx; but then, .pdf                     If R is reflexive, then xRy means yRx; but then, .pdf
If R is reflexive, then xRy means yRx; but then, .pdf
 
H2O HBr H2 due to hydrogen bonding and then .pdf
                     H2O  HBr  H2  due to hydrogen bonding and then .pdf                     H2O  HBr  H2  due to hydrogen bonding and then .pdf
H2O HBr H2 due to hydrogen bonding and then .pdf
 

Recently uploaded

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 

Recently uploaded (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 

package length; A Length is an object that has a length and .pdf

  • 1. package length; /** * A Length is an object that has a length and a unit, can be converted to * meters, can be added to other Lengths, and can be compared to other Lengths. * * @author Tom Bylander */ publicabstractclass Length implements Comparable { /** * The length in the units of this object. */ privatedouble length; /** * Store the length in this Length. * * @param length */ public Length(double length) { this.length = length; } /** * This should add the other Length to this Length object. * * @param other */ publicabstractvoid add(Length other); /** * This should return a different String if the length is exactly 1.0. * * @return the correct name of the unit of this Length object. */ publicabstract String getUnit(); /** * @return the length in meters */
  • 2. publicabstractdouble toMeters(); /** * @return the length of this Length object. */ publicdouble getLength() { return length; } /** * Set the length of this Length object. * * @param length * length in the units of this object */ publicvoid setLength(double length) { this.length = length; } /** * Compare this Length object to the other one. */ publicint compareTo(Length other) { if((this.toMeters() - other.toMeters()) < 0) return -1; elseif((this.toMeters() - other.toMeters()) > 0) return 1; return 0; } /** * @return a String that includes the class name, the length, and the unit. */ public String toString() { returnthis.getClass() + ": " + getLength() + " " + getUnit(); } } package length; publicclass Meter extends Length{ /**
  • 3. * Parameterized constructor * @param length */ public Meter(double length) { super(length); } @Override publicvoid add(Length other) { setLength(other.toMeters() + getLength()); } @Override public String getUnit() { if(getLength() == 1.0) return "meter"; else return "meters"; } @Override publicdouble toMeters() { return getLength(); } } package length; publicclass Inch extends Length { /** * 1 inch = 0.0254 meters */ publicstaticfinaldoubleMETERS_PER_INCH = 0.0254; /** * Parameterized constructor * @param length */ public Inch(double length) { super(length); } @Override
  • 4. publicvoid add(Length other) { double otherToInch = other.toMeters() / METERS_PER_INCH; setLength(otherToInch + getLength()); } @Override public String getUnit() { if(getLength() == 1.0) return "inch"; else return "inches"; } @Override publicdouble toMeters() { return (getLength() * METERS_PER_INCH); } } package length; publicclass Foot extends Length { /** * 1 foot = 0.3048 meters */ publicstaticfinaldoubleMETERS_PER_FOOT = 0.3048; /** * Parameterized constructor * @param length */ public Foot(double length) { super(length); } @Override publicvoid add(Length other) { double otherToFoot = other.toMeters() / METERS_PER_FOOT; setLength(otherToFoot + getLength()); } @Override public String getUnit() {
  • 5. if(getLength() == 1.0) return "foot"; else return "feet"; } @Override publicdouble toMeters() { return (getLength() * METERS_PER_FOOT); } } package length; publicclass Yard extends Length{ /** * 1 yard = 0.9144 meters */ publicstaticfinaldoubleMETERS_PER_YARD = 0.9144; /** * Parameterized constructor * @param length */ public Yard(double length) { super(length); } @Override publicvoid add(Length other) { double otherToYard = other.toMeters() / METERS_PER_YARD; setLength(otherToYard + getLength()); } @Override public String getUnit() { if(getLength() == 1.0) return "yard"; else return "yards"; } @Override
  • 6. publicdouble toMeters() { return (getLength() * METERS_PER_YARD); } } package length; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; publicclass LengthTest { publicstaticvoid main(String[] args) { Scanner in = null; try { in = new Scanner(new File("data.txt")); } catch (FileNotFoundException exception) { thrownew RuntimeException("failed to open data.txt"); } //ArrayList to hold Length objects List lengthList = new ArrayList(); while (in.hasNextDouble()) { double value = in.nextDouble(); String unit = in.next(); Length length = null; //Create the right type of Length object and store it in length if(unit.equalsIgnoreCase("meter") || unit.equalsIgnoreCase("meters")) length = new Meter(value); elseif(unit.equalsIgnoreCase("inch") || unit.equalsIgnoreCase("inches")) length = new Inch(value); elseif(unit.equalsIgnoreCase("foot") || unit.equalsIgnoreCase("feet")) length = new Foot(value); elseif(unit.equalsIgnoreCase("yard") || unit.equalsIgnoreCase("yards")) length = new Yard(value); System.out.println(length); //Add length to arraylist
  • 7. lengthList.add(length); } // Close scanner object in.close(); //Display minimum and maximum length Collections.sort(lengthList); System.out.println(" Minimum is " + lengthList.get(0)); System.out.println("Maximum is " + lengthList.get(lengthList.size() - 1)); //Sum of Lengths Adding from First to Last Meter meter = new Meter(0); Inch inch = new Inch(0); Foot foot = new Foot(0); Yard yard = new Yard(0); for (Length length : lengthList) { meter.add(length); inch.add(length); foot.add(length); yard.add(length); } System.out.println(" Sum of Lengths Adding from First to Last"); System.out.println(meter); System.out.println(inch); System.out.println(foot); System.out.println(yard); //Sum of Lengths Adding from Last to First System.out.println(" Sum of Lengths Adding from Last to First"); meter = new Meter(0); inch = new Inch(0); foot = new Foot(0); yard = new Yard(0); //Reverse list to calculate sum from last to first Collections.reverse(lengthList); for (Length length : lengthList) { meter.add(length); inch.add(length); foot.add(length);
  • 8. yard.add(length); } System.out.println(meter); System.out.println(inch); System.out.println(foot); System.out.println(yard); } } SAMPLE OUTPUT: class length.Meter: 1.0 meter class length.Inch: 1.0 inch class length.Foot: 1.0 foot class length.Yard: 1.0 yard class length.Meter: 401.336 meters class length.Inch: 15839.0 inches class length.Foot: 1319.0 feet class length.Yard: 439.0 yards Minimum is class length.Inch: 1.0 inch Maximum is class length.Inch: 15839.0 inches Sum of Lengths Adding from First to Last class length.Meter: 1609.344 meters class length.Inch: 63360.00000000001 inches class length.Foot: 5280.0 feet class length.Yard: 1760.0 yards Sum of Lengths Adding from Last to First class length.Meter: 1609.3439999999996 meters class length.Inch: 63360.0 inches class length.Foot: 5279.999999999999 feet class length.Yard: 1760.0 yards Solution package length; /** * A Length is an object that has a length and a unit, can be converted to * meters, can be added to other Lengths, and can be compared to other Lengths.
  • 9. * * @author Tom Bylander */ publicabstractclass Length implements Comparable { /** * The length in the units of this object. */ privatedouble length; /** * Store the length in this Length. * * @param length */ public Length(double length) { this.length = length; } /** * This should add the other Length to this Length object. * * @param other */ publicabstractvoid add(Length other); /** * This should return a different String if the length is exactly 1.0. * * @return the correct name of the unit of this Length object. */ publicabstract String getUnit(); /** * @return the length in meters */ publicabstractdouble toMeters(); /** * @return the length of this Length object. */ publicdouble getLength() {
  • 10. return length; } /** * Set the length of this Length object. * * @param length * length in the units of this object */ publicvoid setLength(double length) { this.length = length; } /** * Compare this Length object to the other one. */ publicint compareTo(Length other) { if((this.toMeters() - other.toMeters()) < 0) return -1; elseif((this.toMeters() - other.toMeters()) > 0) return 1; return 0; } /** * @return a String that includes the class name, the length, and the unit. */ public String toString() { returnthis.getClass() + ": " + getLength() + " " + getUnit(); } } package length; publicclass Meter extends Length{ /** * Parameterized constructor * @param length */ public Meter(double length) { super(length);
  • 11. } @Override publicvoid add(Length other) { setLength(other.toMeters() + getLength()); } @Override public String getUnit() { if(getLength() == 1.0) return "meter"; else return "meters"; } @Override publicdouble toMeters() { return getLength(); } } package length; publicclass Inch extends Length { /** * 1 inch = 0.0254 meters */ publicstaticfinaldoubleMETERS_PER_INCH = 0.0254; /** * Parameterized constructor * @param length */ public Inch(double length) { super(length); } @Override publicvoid add(Length other) { double otherToInch = other.toMeters() / METERS_PER_INCH; setLength(otherToInch + getLength()); } @Override
  • 12. public String getUnit() { if(getLength() == 1.0) return "inch"; else return "inches"; } @Override publicdouble toMeters() { return (getLength() * METERS_PER_INCH); } } package length; publicclass Foot extends Length { /** * 1 foot = 0.3048 meters */ publicstaticfinaldoubleMETERS_PER_FOOT = 0.3048; /** * Parameterized constructor * @param length */ public Foot(double length) { super(length); } @Override publicvoid add(Length other) { double otherToFoot = other.toMeters() / METERS_PER_FOOT; setLength(otherToFoot + getLength()); } @Override public String getUnit() { if(getLength() == 1.0) return "foot"; else return "feet"; }
  • 13. @Override publicdouble toMeters() { return (getLength() * METERS_PER_FOOT); } } package length; publicclass Yard extends Length{ /** * 1 yard = 0.9144 meters */ publicstaticfinaldoubleMETERS_PER_YARD = 0.9144; /** * Parameterized constructor * @param length */ public Yard(double length) { super(length); } @Override publicvoid add(Length other) { double otherToYard = other.toMeters() / METERS_PER_YARD; setLength(otherToYard + getLength()); } @Override public String getUnit() { if(getLength() == 1.0) return "yard"; else return "yards"; } @Override publicdouble toMeters() { return (getLength() * METERS_PER_YARD); } } package length;
  • 14. import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; publicclass LengthTest { publicstaticvoid main(String[] args) { Scanner in = null; try { in = new Scanner(new File("data.txt")); } catch (FileNotFoundException exception) { thrownew RuntimeException("failed to open data.txt"); } //ArrayList to hold Length objects List lengthList = new ArrayList(); while (in.hasNextDouble()) { double value = in.nextDouble(); String unit = in.next(); Length length = null; //Create the right type of Length object and store it in length if(unit.equalsIgnoreCase("meter") || unit.equalsIgnoreCase("meters")) length = new Meter(value); elseif(unit.equalsIgnoreCase("inch") || unit.equalsIgnoreCase("inches")) length = new Inch(value); elseif(unit.equalsIgnoreCase("foot") || unit.equalsIgnoreCase("feet")) length = new Foot(value); elseif(unit.equalsIgnoreCase("yard") || unit.equalsIgnoreCase("yards")) length = new Yard(value); System.out.println(length); //Add length to arraylist lengthList.add(length); } // Close scanner object in.close(); //Display minimum and maximum length
  • 15. Collections.sort(lengthList); System.out.println(" Minimum is " + lengthList.get(0)); System.out.println("Maximum is " + lengthList.get(lengthList.size() - 1)); //Sum of Lengths Adding from First to Last Meter meter = new Meter(0); Inch inch = new Inch(0); Foot foot = new Foot(0); Yard yard = new Yard(0); for (Length length : lengthList) { meter.add(length); inch.add(length); foot.add(length); yard.add(length); } System.out.println(" Sum of Lengths Adding from First to Last"); System.out.println(meter); System.out.println(inch); System.out.println(foot); System.out.println(yard); //Sum of Lengths Adding from Last to First System.out.println(" Sum of Lengths Adding from Last to First"); meter = new Meter(0); inch = new Inch(0); foot = new Foot(0); yard = new Yard(0); //Reverse list to calculate sum from last to first Collections.reverse(lengthList); for (Length length : lengthList) { meter.add(length); inch.add(length); foot.add(length); yard.add(length); } System.out.println(meter); System.out.println(inch); System.out.println(foot);
  • 16. System.out.println(yard); } } SAMPLE OUTPUT: class length.Meter: 1.0 meter class length.Inch: 1.0 inch class length.Foot: 1.0 foot class length.Yard: 1.0 yard class length.Meter: 401.336 meters class length.Inch: 15839.0 inches class length.Foot: 1319.0 feet class length.Yard: 439.0 yards Minimum is class length.Inch: 1.0 inch Maximum is class length.Inch: 15839.0 inches Sum of Lengths Adding from First to Last class length.Meter: 1609.344 meters class length.Inch: 63360.00000000001 inches class length.Foot: 5280.0 feet class length.Yard: 1760.0 yards Sum of Lengths Adding from Last to First class length.Meter: 1609.3439999999996 meters class length.Inch: 63360.0 inches class length.Foot: 5279.999999999999 feet class length.Yard: 1760.0 yards