Write a program that asks the user to enter three names, andthen displays the na
ID: 3614506 • Letter: W
Question
Write a program that asks the user to enter three names, andthen displays the names sorted in alphabetical order. Assume thatnone of the names are the same. For example, if the user entered"Charlie," "Leslie," and "Andy," the program would display: Andy Charlie Leslie Write a program that asks the user to enter three names, andthen displays the names sorted in alphabetical order. Assume thatnone of the names are the same. For example, if the user entered"Charlie," "Leslie," and "Andy," the program would display: Andy Charlie LeslieExplanation / Answer
1. You need to declare 3 strings variable. 2. Ask user to input the 3 names. 3. Use compareTo to compare strings. Youcannot use = = . 4. So when str1.compareTo(str2) > 0means that the alphabetical order of first string is larger thansecond string, therefore we swap their position. 5. We have to compare 3 sets, which are 1st name & 2nd name,1st name & 3rd name, 2nd name & 3rd name. 6. So, if str1 is greater than str2, do temp=str1; the variable str1 shouldstore str2, therefore we save value of str1 into another temporaryvariable, which is temp. 7. Next, we save value of str2 into str1, which is str1=str2; 8. Lastly, weput back value of str1 which is in temp into str2 by str2=temp; 9. Forexample, let str1 be Belinda and str2 be Alex. After temp=str1; str1=str2; str2=temp; their positionare being swapped and the output will be str1=Alex andstr2=Belinda
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.