Q:

Java program to read and add two distances using class

belongs to collection: Java Class and Object Programs

0

Example:

    Input:
    Enter first distance: 
    Enter feet: 20
    Enter inches: 10
    Enter second distance: 
    Enter feet: 20
    Enter inches: 10

    Output:
    Total distance is:
    Feet: 41	Inches: 8

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

import java.util.*;

//class Distance to read, print and add distance
class Distance {
  private int feet;
  private int inches;

  public void getDistance() {
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter feet: ");
    feet = sc.nextInt();
    System.out.print("Enter inches: ");
    inches = sc.nextInt();
  }
  public void showDistance() {
    System.out.println("Feet: " + feet + "\tInches: " + inches);
  }

  public void addDistance(Distance D1, Distance D2) {
    inches = D1.inches + D2.inches;
    feet = D1.feet + D2.feet + (inches / 12);
    inches = inches % 12;
  }
}

public class AddTwoDistance {
  public static void main(String[] s) {
    try {

      Distance D1 = new Distance();
      Distance D2 = new Distance();
      Distance D3 = new Distance();

      //read first distance
      System.out.println("Enter first distance: ");
      D1.getDistance();

      //read second distance
      System.out.println("Enter second distance: ");
      D2.getDistance();

      //add distances
      D3.addDistance(D1, D2);
      //print distance
      System.out.println("Total distance is:");
      D3.showDistance();
    } catch (Exception e) {
      System.out.println("Exception occurred :" + e.toString());
    }
  }
}

Output

Enter first distance: 
Enter feet: 20
Enter inches: 10
Enter second distance: 
Enter feet: 20
Enter inches: 10
Total distance is:
Feet: 41	Inches: 8

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Class and Object Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to create members with private access... >>
<< Java program to check Armstrong number...