线程中的异常 - java.util.InputMismatchException

时间:2012-12-07 04:41:14

标签: java string sorting polymorphism

我正在尝试读入并排序字符串并且收到错误。我修改了程序,因为第一个答案说,我在运行中进一步,但它不会完成。我是初学者,所以请明确要改变什么。

我收到此错误:

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();

    **}**

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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();

    }