In: Computer Science
Write java program that will ask for the user for 2 input lines
and print out all words that occur 1 or
more times on both lines (case sensitive). Write this without
arrays and method. Here is a sample run:
<Output>
Enter two lines to process.
The quick brown fox jumps over a lazy dog
The fox hound outruns the lazy dog
The words that occur on both lines are: The fox lazy dog
Java Code:
import java.io.*;
import java.util.Arrays;
import java.util.ArrayList;
class WordsCommon
{
public static void main (String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
int i,j;
System.out.print("Enter the first sentence: ");
String str1 = br.readLine();
System.out.print("Enter the second sentence: ");
String str2 = br.readLine();
//Store all the words of the first sentence in a string array
String[] words1 = str1.split("\\s+");
//Store all the words of the second sentence in a string array
String[] words2 = str2.split("\\s+");
//Converting array into array list
ArrayList<String> array1= new ArrayList<String>(Arrays.asList(words1));
ArrayList<String> array2= new ArrayList<String>(Arrays.asList(words2));
//Find common elements
array1.retainAll(array2);
String s = String.join(" ", array1);
System.out.println("The words that occurs on both lines are: "+ s);
}
}
Output:
Enter the first sentence: The quick brown fox jumps over a lazy dog
Enter the second sentence: The fox hound outruns the lazy dog
The words that occurs on both lines are: The fox lazy dog
How to run the code:
1) Copy paste the code in notepad and save the file as "WordsCommon.java".
2) Go to command prompt, go to the directory where the file is saved and compile the java code by typing "javac WordsCommon.java"
3) Then run the code by typing "java WordsCommon"
4) Then input the two sentences
5) Output will be generated