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