49.7k views
1 vote
Write a program that uses a Scanner object to read two strings from the user’s keyboard. Display each string, along with its width, on two separate lines. Then create a new string by joining the two strings with a space between them. Display the new string and its length on a new separate line.

1 Answer

3 votes

Answer:

// here is code in java.

import java.util.*;

class Main

{

public static void main (String[] args) throws java.lang.Exception

{

try{

// create 3 string variables

String st1,st2,st3;

// scanner object to read input

Scanner scr=new Scanner(System.in);

System.out.print("enter the first string:");

// read first string

st1=scr.nextLine();

System.out.print("enter the second string:");

// read second string

st2=scr.nextLine();

// print 1st string and its length

System.out.println(st1+" "+st1.length());

// print 2nd string and its length

System.out.println(st2+" "+st2.length());

// create 3rd string by joining two string with a space between

st3=st1+" "+st2;

//// print 3rd string and its length

System.out.println(st3+" "+st3.length());

}catch(Exception ex){

return;}

}

}

Step-by-step explanation:

Create three string variables.Read the 1st string and assign it to variable "st1" , read 2nd string and assign it to variable "st2".Find the length of 1st and 2nd string and then print "st1" & its length.Similarly do it for 2nd string, print "st2" and its length in a line. Join the first two string with a space in between them. find its length and print the "st3" and its length in a line.

Output:

enter the first string:

hello

enter the second string:

alex

hello 5

alex 4

hello alex 10

User Yusuf Demirag
by
5.4k points