Exercise 5. Write a program that uses a Scanner to read two words. The program w
ID: 3933934 • Letter: E
Question
Exercise 5. Write a program that uses a Scanner to read two words. The program will detect words that are the same (case does not matter). If the words are not the same, it will print a message with the length of each word. Test this program with two outputs - one word that is the same and one that is different.
Please type a word: abcde
Please type a word: abcdf
The words are: abcde and abcdf. These words are not the same. abcde has 5 letters and abcdf has 5 letters.
Please type a word: abcde
Please type a word: abcde
The words are: abcde and abcde. These words are the same.
Exercise 5. Write a program that uses a Scanner to read two words. The program will detect words that are the same (case does not matter). If the words are not the same, it will print a message with the length of each word. Test this program with two outputs- one word that is the same and one that is different. Please type a word: abcde Please type a word: abcdf The words are: abcde and abcdf. These words are not the same. abcde has 5 ietters and bcdf has 5 letters. Please type a word: abcde Please type a word: abcde The words are: abcde and abcde. These words are the same.Explanation / Answer
import java.util.Scanner;
public class Test{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Please type a word: ");
String word1 = in.next();
System.out.print("Please type a word: ");
String word2 = in.next();
System.out.print("The words are: " + word1 + " and " + word2 + ". ");
if(word1.compareToIgnoreCase(word2) == 0) System.out.print("These words are the same.");
else System.out.print("These words are not the same. " + word1 + " has " + word1.length() + " letters and " + word2 + " has " + word2.length() + " letters.");
}
}