In: Computer Science
Write a java code that allows the user to input any word/name from the console (10 words/names only) and then sorts and alphabetizes them into an array without using predefined methods (.compareTo(), or any sorter functions) and then print out the results.
you must have three methods that can:
Compare multiple strings
Swap elements
Sort and alphabetize string
***REMEMBER DO NOT USE ANY PRE-DEFINED METHODS***
Example of how the code should work:
Enter names/words (10 only):
"james, john, alex, aaron, brandon, nick, gian, deavan, daniel, jake"
*sorted output*:
"Aaron, Alex, Brandon, Daniel, Deavan, Gian, Jake, James, John, Nick"
JAVA CODE:
import java.util.*;
class Jav{
//method to compare strings
static int Compare(String a,String b)
{
int l1 = a.length();
int l2 = b.length();
int len = Math.min(l1, l2);
int i = 0;
while (i < len) {
int x = (int) a.charAt(i);
int y = (int) b.charAt(i);
if (x > y)
return 1;
else if (x < y)
return 0;
i++;
}
if (l2 < l1)
return 1;
else
return 0;
}
//method to sort, alphabetize and print strings
static void Sort(String str[],int count)
{
String temp;
//sorting strings
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
//comparing strings to sort
if (Compare(str[i], str[j]) == 1) {
//swapping the strings
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
//alphabetize strings
for (int i = 0; i < count; i++)
{
str[i] = str[i].substring(0, 1).toUpperCase() + str[i].substring(1, str[i].length());
}
//printing strings
System.out.print("Sorted String: ");
for (int i = 0; i <= count - 1; i++)
{
System.out.print(str[i]);
if (i!=count-1)
System.out.print(", ");
}
}
//main method
public static void main(String[] args) {
int count;
Scanner scan = new Scanner(System.in);
//prompt to take input
System.out.print("Enter number of strings you would like to enter:\n");
count = scan.nextInt();
String str[] = new String[count];
//enter inputs line by line
System.out.println("Enter the Strings one by one:");
scan.nextLine();
for(int i = 0; i < count; i++)
{
str[i] = scan.nextLine();
}
scan.close();
//function call for Sorting the strings
Sort(str, count);
}
}
SAMPLE RUN:
code:
output: