-1

我正在尝试读取字符串并对其进行排序,但出现错误。我按照第一个答案的说法修改了程序,我在运行中走得更远,但它不会完成。我是初学者,所以请清楚要更改的内容。

我收到此错误:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at hw05.Strings.main(Strings.java:32)
Java Result: 1

The line with error is starred.

package hw05;

/**
 *Demonstrates selectionSort on an array of strings.
 * 
 * @author Maggie Erwin
 */
import java.util.Scanner;

public class Strings {

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

        String[] stringList;
        Integer[] intList;
        int size;

        Scanner scan = new Scanner(System.in);

        System.out.print("\nHow many strings do you want to sort? ");
        size = scan.nextInt();
        int sizeInInt = Integer.valueOf(size);
        stringList = new String[sizeInInt];
        intList= new Integer[sizeInInt]; // Initialize intList

        System.out.println("\nEnter the strings...");
        for (int i = 0; i < size; i++) {
                intList[i] = scan.nextInt();
            }
        Sorting.selectionSort(stringList);

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

    **}**
4

2 回答 2

1

你还没有像你初始化的那样初始化intList变量stringList

String[] stringList;
Integer[] intList;
....
stringList = new String[sizeInInt];  //you initialized it in your code
intList = new Integer[sizeInInt];    // missing in your code
于 2012-12-07T04:44:17.490 回答
0

这个错误解释了一切。你需要先初始化sizeInInt。所以它看起来像这样:

public static void main(String[] args) {

        String[] stringList;
        Integer[] intList;
        int size;

        Scanner scan = new Scanner(System.in);

        System.out.print("\nHow many strings do you want to sort? ");
        size = scan.nextInt();
        int sizeInInt = Integer.valueOf(size);
        stringList = new String[sizeInInt];
        intList= new Integer[sizeInInt]; // Initialize intList

        System.out.println("\nEnter the strings...");
        for (int i = 0; i < size; i++) {
                **intList**[i] = scan.nextInt();
            }
        Sorting.selectionSort(stringList);

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

    }
于 2012-12-07T04:43:56.163 回答