在Java中排序字符串数组 [英] Sorting an array of strings in Java

查看:126
本文介绍了在Java中排序字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户可以使用字符串数组。他们可以向数组添加字符串,从数组中删除字符串,在数组中搜索字符串,最终他们将能够对数组进行排序。排序是什么是搞砸我。我尝试了几种不同的方法。第一种方法是将数组转换为ArrayList并使用Collections对ArrayList进行排序,这将被转换回静态类数组。它不工作。我尝试的第二种方法是迭代遍历数组,并尝试只排序由用户添加的字符串,而不是数组中的一切(因为在数组中有一些空值)。也许我应该遍历数组,然后将非空值存储到一个新的数组,然后我可以排序?但是如果我想在排序新数组后添加更多的字符串呢?这就是为什么我停止与第二个解决方案。第三个尝试是使用Arrays.sort()在我的数组,但由于某些原因,它不工作。



以下是例外:

 线程main java.lang.NullPointerException 
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)
在java。 util.ComparableTimSort.sort(ComparableTimSort.java:146)
在java.util.Arrays.sort(Arrays.java:472)
在java.util.Collections.sort(Collections.java:155)
at testingSearch.sortArray(testingSearch.java:93)
at testingSearch.main(testingSearch.java:42)

这是我的代码:

  import java.util.Scanner; 
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class testingSearch {

static String [] strArray;
static {
strArray = new String [5];
}
public static void main(String [] args){
Scanner input = new Scanner(System.in);

while(true){
System.out.println(1。向字符串数组添加字符串。
System.out.println(2.从字符串数组中删除字符串);
System.out.println(3。在字符串数组中显示字符串);
System.out.println(4。搜索字符串数组的字符串。
System.out.println(5.。字符串数组中的字符串排序。

int userChoice = 0;
userChoice = input.nextInt();

switch(userChoice){
case 1:
addString();
break;
case 2:
removeString();
break;
case 3:
displayStrings();
break;
case 4:
searchArray();
break;
case 5:
sortArray();
break;
}
}

}

public static void addString(){
Scanner input = new Scanner(System.in);
System.out.println(要添加什么字符串?
String userInput;
userInput = input.nextLine();
ArrayList< String> stringList = new ArrayList< String> (Arrays.asList(strArray));
stringList.add(userInput);
strArray = stringList.toArray(strArray);
}

public static void removeString(){
扫描仪输入= new Scanner(System.in);
System.out.println(要删除什么字符串?
String userInput;
userInput = input.nextLine();
ArrayList< String> stringList = new ArrayList< String> (Arrays.asList(strArray));
stringList.remove(userInput);
strArray = stringList.toArray(strArray);
}

public static void displayStrings(){
for(String s:strArray){
if(!(s == null)){
System.out.println(s);
}
}
}

public static void searchArray(){
Scanner input = new Scanner(System.in);
System.out.println(要搜索数组什么字符串?);
String userInput;
userInput = input.nextLine();
ArrayList< String> stringList = new ArrayList< String>(Arrays.asList(strArray));
if(stringList.contains(userInput)){
System.out.println(字符串数组包含该字符串!
}
else {
System.out.println(字符串数组不包含该字符串...);
}
}

public static void sortArray(){
/ * ArrayList< String> stringList = new ArrayList< String> (Arrays.asList(strArray));
Collections.sort(stringList);
strArray = stringList.toArray(strArray); * /

/ * for(String s:strArray){
if(!(s == null)){
Arrays.sort(strArray);
}
} * /

List< String> stringList = new ArrayList< String>(Arrays.asList(strArray));
Collections.sort(stringList);
strArray = stringList.toArray(strArray);

//Arrays.sort(strArray);

}

}


解决方案

获得 NullPointerException 的原因可以通过 javadoc for Arrays#sort() (强调我的):


根据元素的自然排序,按指定的升序排列对象数组。 数组中的所有元素都必须实现可比较接口。



$ b因为 Arrays.sort()预期可比较的元素而不是 null 值,当方法尝试调用 compareTo()时,最终会出现 NullPointerException / p>

解决这个问题的方法是简单地确保数组中的所有 null 替换为非 - null ,例如。因此,在创建时和删除 String 并将 null 元素设置为 。然而,这个解决方案可能不会对你的代码执行得太好,因为它需要在每个 String 之后的另一个循环,这可能会变得繁重。至少它不需要你创建一堆对象,由于 String 池的魔力,所以它比你可能做一个不同的对象。



一个更好的解决方案是简单地使用 ArrayList< String> 毕竟,你已经使用一个来管理 addString() removeString(),所以你会有更少从数组转换到 ArrayList 然后回来做。此外,在排序时不需要担心NPE(至少对于您的用例;将 null 添加到集合在排序时仍然会导致NPE)。



你也可以使用一个原始数组,但是管理它会让人讨厌,所以我不会推荐。如果你这样做,你不必担心NPE虽然。


The user is allowed to play with an array of strings. They can add strings to the array, remove strings from the array, search for strings in the array, and eventually they will be able to sort the array. The sorting is what is messing me up. I've tried a few different approaches. The first approach was to convert the array into an ArrayList and use Collections to sort the ArrayList, which would be converted back into the static class array. It doesn't work. The second approach I tried was to iterate through the array and try to sort only the strings added by the user instead of everything in the array (since there are some null values in the array). Perhaps I should iterate through the array and then store the non-null values into a new array that I can then sort? But what if I want to add more strings after sorting the new array? That's why I stopped with the second solution. The third attempt was to use Arrays.sort() on my array but for some reason it does not work.

Here is the exception:

 Exception in thread "main" java.lang.NullPointerException 
    at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290) 
    at java.util.ComparableTimSort.sort(ComparableTimSort.java:157) 
    at java.util.ComparableTimSort.sort(ComparableTimSort.java:146) 
    at java.util.Arrays.sort(Arrays.java:472) 
    at java.util.Collections.sort(Collections.java:155) 
    at testingSearch.sortArray(testingSearch.java:93) 
    at testingSearch.main(testingSearch.java:42) 

Here is my code:

import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class testingSearch {

    static String[] strArray;
    static {
        strArray = new String[5];
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        while(true){
            System.out.println("1. Add string to the string array.");
            System.out.println("2. Remove string from the string array.");
            System.out.println("3. Display strings in string array.");
            System.out.println("4. Search the string array for a string.");
            System.out.println("5. Sort the strings in the string array.");

            int userChoice = 0;
            userChoice = input.nextInt();

            switch(userChoice) {
            case 1:
                addString();
                break;
            case 2:
                removeString();
                break;
            case 3:
                displayStrings();
                break;
            case 4:
                searchArray();
                break;
            case 5:
                sortArray();
                break;
            }
        }

    }

    public static void addString(){
        Scanner input = new Scanner(System.in);
        System.out.println("What string do you want to add?");
        String userInput;
        userInput = input.nextLine();
                ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
        stringList.add(userInput);
        strArray = stringList.toArray(strArray);
    }

    public static void removeString(){
        Scanner input = new Scanner(System.in);
        System.out.println("What string do you want to remove?");
        String userInput;
        userInput = input.nextLine();
        ArrayList<String> stringList = new ArrayList<String>    (Arrays.asList(strArray));
        stringList.remove(userInput);
        strArray = stringList.toArray(strArray);
    }

    public static void displayStrings(){
        for (String s: strArray){
            if (!(s == null)){
                System.out.println(s);
            }
        }
    }

    public static void searchArray(){
        Scanner input = new Scanner(System.in);
        System.out.println("What string do you want to search the array for?");
        String userInput;
        userInput = input.nextLine();
        ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(strArray));
        if (stringList.contains(userInput)){
            System.out.println("The string array contains that string!");
        }
        else {
            System.out.println("The string array does not contain that string...");
        }
    }

    public static void sortArray(){
        /*ArrayList<String> stringList = new ArrayList<String> (Arrays.asList(strArray));
        Collections.sort(stringList);
        strArray = stringList.toArray(strArray);*/

        /*for (String s: strArray) {
            if (!(s == null)){
                Arrays.sort(strArray);
            }
        }*/

        List<String> stringList = new ArrayList<String>(Arrays.asList(strArray));
        Collections.sort(stringList);
        strArray = stringList.toArray(strArray);

        //Arrays.sort(strArray);

    }

}

解决方案

The reason you're getting NullPointerExceptions can be explained by the javadoc for Arrays#sort() (emphasis mine):

Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface.

Because Arrays.sort() expects Comparable elements and not null values, you end up with a NullPointerException when the method tries to call compareTo().

The fix-this-now way of solving this would be to simply make sure all null elements in your array are replaced with something non-null, such as "". So loop through your array at creation and after removing a String and set null elements to "". However, this solution probably wouldn't perform too well for your code, as it requires another loop after every String is removed, which could grow onerous. At least it won't require you to create a bunch of objects, due to the magic of the String pool, so it's a bit better than what you might do with a different object.

A better solution would be to simply use ArrayList<String> instead of a raw array; after all, you're already using one to manage addString() and removeString(), so you would have less converting from array to ArrayList and back to do. In addition, you wouldn't need to worry about NPEs when sorting (at least for your use case; adding null to a Collection would still result in NPEs when sorting).

You can also just use a raw array, but managing that would get kind of annoying, so I wouldn't recommend that. If you do it right you won't have to worry about NPEs though.

这篇关于在Java中排序字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆