import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String[] arr=new String[n];
for(int i=0;i<=arr.length;i++) {
arr[i]=sc.nextLine();
}
lexical_sort(arr);
display(arr);
sc.close();
}
public static void display(String[] arr) {
for(int i=0;i<arr.length;i++) {
System.out.println(arr[i]+" ");
}
}
public static void lexical_sort(String[] arr) {
for(int i=0;i<arr.length;i++) {
for(int j=i+1;j<arr.length;j++) {
if(arr[i].compareToIgnoreCase(arr[j])>0 && arr[i].length()<arr[j].length()) {
String temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
}
here in this program i am getting exception
when i try to take input 3 strings but i get only 2 string to input the value
Getting exception
you havent read my doubt properly
my doubt is that my program is asking for the input n-1 times when i enter n inputs
for eg when i enter 3 i only get 2 inputs thats the problrm in my code
That is happening because you are using sc.nextLine() to take the input. Use sc.next() to take the string input.
And you are receiving the exception as Array Index Out of bounds.
To resolve that make the changes as suggested in my the previous message.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.