THINK FIRST·CODE LATER

← All labs

Comparing two words

Problem

CompareWords reads two words and prints how Java compares them: their lengths, equals, equalsIgnoreCase, compareTo, compareToIgnoreCase, whether the first comes before the second in the dictionary, and the first letter of each with its character code.

For the input

apple Banana

the program prints

Lengths: 5 and 6
Same length: false
equals: false
equalsIgnoreCase: false
compareTo: 31
compareToIgnoreCase: -1
apple comes before Banana in the dictionary: true
First letters: a (97) and B (66)

Never compare strings with ==. What does the sign of compareTo tell you?

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l5-9-data-1.txt

apple Banana
What your program must print for l5-9-data-1.txt
Lengths: 5 and 6
Same length: false
equals: false
equalsIgnoreCase: false
compareTo: 31
compareToIgnoreCase: -1
apple comes before Banana in the dictionary: true
First letters: a (97) and B (66)

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l5-9-data-1.txt

Windows PowerShell does not understand <:

Get-Content l5-9-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.