Java 字符串排序错误

标签 java string sorting polymorphism

我正在尝试读取字符串并对它们进行排序。我收到了许多错误,这些错误在下面的代码中标有星号。你能告诉我如何修复这些错误吗?

package hw05;

/*
Demonstrates selectionSort on an array of strings.
*/
import java.util.Scanner;

public class Strings {
    // --------------------------------------------
    // Reads in an array of strings, sorts them,
    // then prints them in sorted order.
    // --------------------------------------------
    public static void main(String[] args) {

        String[] stringList;
        String size;

        Scanner scan = new Scanner(System.in);

        System.out.print("\nHow many strings do you want to sort? ");
        size = scan.nextLine();
        **stringList = new String[size];**

        System.out.println("\nEnter the strings...");
        **for (String i = 0; i < size; i++)
            stringList[i] = scan.nextLine();**
        Sorting.selectionSort(stringList);

        System.out.println("\nYour strings in sorted order...");
        **for (String i = 0; i < size; i++)
            System.out.print(stringList[i] + " ");**
        System.out.println();

    }
}

最佳答案

stringList = new String[size];

大小应该是int而不是String。您需要执行如下操作:

int sizeInInt = Integer.valueOf(size); // This may throw NumberFormatException, wrap it in try/catch.

stringList = new String[sizeInInt ];

(或)

将大小更改为 int 并执行 nextInt() 而不是 nextLine()

我建议在执行 nextInt() (或)nextLine() 之前先执行 hasNext(),否则您可能会得到 NoSuchElementException

关于Java 字符串排序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13756760/

相关文章:

java - 为什么我的 Java 代码不获取 JTextfield 的值?

java - 返回值中的 '&'字符是什么意思?

java - 当单词不以 "qu"开头时,如何使此方法返回 false ?

c# - 对字符串属性进行排序,例如 Integer LINQ

javascript - 使用带有下拉列表的事件监听器按属性对对象数组进行排序

java - GAE 日志字段中时间值的确切含义是什么?

java - EditText 按需小部件

android - 如何从字节数组中逐字节获取

C++ 查找字符数组中的最后一个字符

java - 按从最高-> 最低的每个字符串解析的整数对 ArrayList<String> 进行排序?