简体   繁体   中英

Sorting an array of Strings with some requirements in Java

I was asked to make a program which takes an array of string and sort it alphabetically. The program should not accept a string with digit or a string of length bigger than 10. If a string does not fulfill requirements the program tells to user to enter another on. After that, all strings will be turn into uppercases strings, and we sort the array. Here's my program, but it doesn't run quite well. It does compile but if a string contains digit or if the length is bigger than 10, it stop and does not ask the user to enter another string. I've tried to do it as asked but I end with an infinite loop that's why I've put a Sys.exit – I wan't to know fist if this program is good or if someone has a more simple way to that. How to modify this program the way that the user is asked to enter another string when one entered is wrong? Any advise or any alternative program. Thanks.

static boolean arrayFilter(String[] str) {
  for (int i=0 ; i < str.length ; i++) {
    for( char c:str[i].toCharArray()) {
        if((Character.isDigit(c))||(str[i].length()>=10)) 
            return false;
        }
  }
    return true;
}
static void swap(int i,int j,String[] str) {
    String tmp;
        tmp=str[i];
        str[i]=str[j];
        str[j]=tmp;
    }

static String[] capitalize(String[] str) {
    for(int i=0;i<str.length;i++) {
            str[i]=str[i].toUpperCase();
            }
        return str;
}   
static String[] triTab(String[] str) {
    if(arrayFilter(str)==false) {
        System.out.println("Wrong string array, please enter list of string without digit and length at most 10");
        System.exit(0);
        }
    else {
    str=capitalize(str);
    for(int i=0;i<str.length;i++) {
        for(int j=i+1;j<str.length;j++) {
            if(str[i].compareTo(str[j])>0)
                swap(i,j,str);
                }
        }}
  return str;
}

} ```

You actually have several problems.

First, move your check for a valid array when someone enters it.

// prompt for use array first time.
while (arrayFilter(str) == false) { // or while(!ArrayFilter(str)) {
    System.out.println(
            "Wrong string array, please enter list of string without digit and length at most 10");
    
    // prompt for new array
    // the while loop will exit when the array is valid.
}
// Array okay so invoke the sort method.

The other problem is that you are changing the nature of the array. They are now all uppercase. Instead of using compareTo use compareToIgnoreCase . Then you can eliminate the method for converting to all uppercase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM