2012-12-07 47 views
-1

我想閱讀和排序字符串,我得到一個錯誤。第一回答說我修改了程序,並且我在跑步中進一步完成,但不會完成。我是初學者,所以請清楚要改變什麼。異常在線程 - java.util.InputMismatchException

我收到此錯誤:

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

    **}** 
+1

你必須在使用前實際創建數組。 –

+0

你在哪裏創建了Integer數組對象?看起來有趣的是,你將數據存儲在Integer數組中,而實際上你正在對String數組進行排序。 –

回答

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

    } 
+0

我現在收到一個新的錯誤,請你看看嗎? –

1

您還沒有初始化的變量intListstringList你已經初始化

String[] stringList; 
Integer[] intList; 
.... 
stringList = new String[sizeInInt]; //you initialized it in your code 
intList = new Integer[sizeInInt]; // missing in your code 
相關問題