Computer Science, asked by shadowkingt0321, 5 hours ago

3. WAP to accept the two lengths in cm and mm, add the length to print the sum.
Example:
INPUT: Length 1 = 7cm 6mm Length 2 = 3cm 9mm
OUTPUT: Sum of length = 11cm 5mm

Answers

Answered by anindyaadhikari13
1

Solution.

Here, I have assumed that the length are not in double type, like - 7.5 cm 6 mm and the length in cm must be written before mm.

The Co‎‎de -

import java.util.*;

public class SumOfLength{

   public static void main(){

       Scanner sc=new Scanner(System.in);  

       System.out.print("Enter length: ");

       String x[]=sc.nextLine().toLowerCase().replace(" ","").split("cm");

       System.out.print("Enter length: ");

       String y[]=sc.nextLine().toLowerCase().replace(" ","").split("cm");

       x[1]=x[1].replace("mm","");

       y[1]=y[1].replace("mm","");

       int cm=Integer.parseInt(x[0])+Integer.parseInt(y[0]);

       int mm=Integer.parseInt(x[1])+Integer.parseInt(y[1]);

       System.out.println("Sum: "+cm+" cm "+mm+" mm.");

   }

}

Logic.

  • Accept the lengths and store in string.
  • Remove all the spaces from string.
  • Extract the numbers from the string.
  • Add up the length and store them in variables - mm and cm.
  • Display the value of the variables.

See attachment for output.

Attachments:
Similar questions