question archive Given a list of N strings, all of them have the same length M
Subject:Computer SciencePrice:2.84 Bought6
Given a list of N strings, all of them have the same length M. We assume that all characters are ASCII code, residing in 256 positions of the character set (from code 0 to code 255). We want to sort this list of strings in the ascending order. Please make a Java program to solve this problem. Your program should:
1)Ask user to input n, list of n strings, all of them have the same length m.
2)Sort the list of strings in the ascending order.
3)Show the result.
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ListString {
public static void main(String[] args) {
int numString = -1, m = 0;
String temp = "";
ArrayList<String> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of Strings: ");
try{
numString = sc.nextInt();
}
catch(InputMismatchException e){
System.out.print("Not a number");
}
sc.nextLine();
while(list.size() != numString){
System.out.print("Enter String: ");
temp = sc.nextLine();
if(list.size() < 1){
m = temp.length();
list.add(temp);
}
else{
if(temp.length() != m){
System.out.println("Input is not the same length as M(" + m + ")");
}
else{
list.add(temp);
}
}
}
Collections.sort(list);
System.out.println("Arranged List of Strings:");
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
sc.close();
}
}
Step-by-step explanation
This solution assumes that the input for n is an integer. The input is taken using a scanner. And while number of strings in list is not equal to n then the loop will continue. The M is taken from the first inputted value meaning that the first string length determines the value of m. The strings of correct length are then inserted in an arraylist. Once the loop ends the arraylist elements are sorted using collections.sort and then displayed using a simple for loop.