Do not use arrays or any library sorting method. Declare 3String variables: str1
ID: 3613693 • Letter: D
Question
Do not use arrays or any library sorting method. Declare 3String variables: str1, str2, str3 to initially hold the 3 inputstrings. Then by comparing the strings and swapping the values asnecessary, get the smallest string in str1, the next smallest instr2, and the largest in str3. Here 'smallest' string means the onethat comes first in the usual ordering of strings. (Remember to usethe String compareTo method to compare the strings.)
The underlined strings are entered by the user. The programshould print all the rest!
Explanation / Answer
public class Sort3{ void main(String [] args){ String str1; String str2; String str3; String temp; System.out.println("This program will sort any 3input strings"); System.out.println(" First string: "); str1=args[0]; System.out.println(" Second string: "); str2=args[1]; System.out.println(" Third string: "); str3=args[2]; while(str1.compareTo(str2)>0 ||str2.compareTo(str3)>0 || str1.compareTo(str3)>0 ) { if(str1.compareTo(str2)>0) { temp=str1; str1=str2; str2=temp; } else if(str2.compareTo(str3)>0) { temp=str2; str2=str3; str3=temp; } else { temp=str1; str1=str3; str3=temp; } } System.out.println(" Sorted Strings: " +str1 + " " + str2 + " " + str3); }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.