InterviewSolution
| 1. |
A class Merger concatenates two positive integers that are greater than 0 and produces a newly merged integer.Example: If the first number is 23 and the second is 764, then the concatenated number will be 23764. Some of the members of the class are given below: Class name: Merger Data members/instance variables: n1: long integer to store the first number n2: long integer to store the second number mergNum: long integer to store the merged number Member functions: Merger(): constructor to initialize the data members void readNum(): to accept the values of the data members n1 and n2 voidjoinNum(): to concatenate the numbers n1 and n2 and store it in mergNum void show(): to display the original numbers and the merged number with appropriate messages Specify the class Merger giving the details of the constructor, void readNum(), void joinNum() and void show(). Define the main() function to create an object and call the functions accordingly to enable the task. |
|
Answer» import java util. Scanner; class Merger { long n1; long n2; long mergNum; public Merger() { n1=1; n2=1; mergNum=11; } public void readNum() { Scanner sc=new Scanner(System.in); System.out.print("Enter first number:"); n1=(int)Math.abs(sc.nextLong()); System.out.print("Enter second number:"); n2=(int)Math.abs(sc.nextLong()); if(n1==0) n1=1; if(n2==0) n2=1; } public void joinNum() { String num1 = Long.toString(n1); String num2 = Long.toString(n2); String merged=num1 + num2; mergNum=Long.parseLong(merged); } public void show() { System.out.println("First Number: "+n1): System.out.println("Second Number: "+n2): System.out.println("Merged Number: "+mergNum): } public static void main(String args[]) { Merger obj=new Merger)); obj.readNum(); Obj.joinNum(); obj.show)); } } |
|