2014-09-02 142 views
0

我必須編寫一個程序,讀入一個整數序列,直到輸入'stop',將整數存儲在一個數組中,然後顯示輸入數字的平均值。輸入「stop」時出現輸入不匹配異常,所以它不起作用,但我不知道爲什麼。幫助將不勝感激。在簡單程序中理解InputMismatch異常的問題

import java.util.Scanner;

公共類MeanUsingList {

public void mean() { 

    String s; 
    int n = 0; 
    int i = 1; 
    int[] array = { n }; 

    do { 
     System.out.println("Enter an integer"); 
     Scanner in = new Scanner(System.in); 
     n = in.nextInt(); 
     s = in.nextLine(); 

    } while (s != "stop"); 
    { 
     System.out.println("Enter an integer"); 
     Scanner in2 = new Scanner(System.in); 
     int x = in2.nextInt(); 
     array[i] = x; 
     i++; 
    } 

    int av = 0; 

    for (int y = 0; y < array.length; y++) { 
     av += array[y]; 
    } 

    System.out.println(av); 

} 

public static void main(String[] args) { 
    MeanUsingList obj = new MeanUsingList(); 
    obj.mean(); 
} 

}

+0

你的程序抓取「停止」,並試圖把它變成它不能做的整數。也許你應該使用'Scanner#hasNextInt()'。另外,作爲一個附註,您不必像現在那樣每次迭代都製作一個新的掃描器。打印提示,創建一個新的掃描儀,打印提示,創建一個新的掃描儀,打印提示,創建一個新的掃描儀... – csmckelvey 2014-09-02 17:39:53

回答

0

首先int[] array = { n };只是創建一個帶有0的數組作爲它的元素。

裏面的邏輯永遠不會執行while (s != "stop");

你想是這樣的

List list = new ArrayList(); 
    //instead of array used arraylist because of dynamic size 

    do { 
     System.out.println("Enter an integer"); 
     Scanner in = new Scanner(System.in); 
     n = in.nextInt(); //get the input 
     list.add(n);  // add to the list 
     Scanner ina = new Scanner(System.in); // need new scanner object 
     s = ina.nextLine(); //ask if want to stop 

    } while (!s.equals("stop")); // if input matches stop exit the loop 

    System.out.println(list); // print the list 

,我建議你學習的基礎知識