2015-02-09 90 views
0

這個問題已經回答了,非常感謝。我無法獲得投入,但最終我能夠做到。我最終使用hasnext代碼來獲得它,所以非常感謝你。如何告訴用戶在輸入字母時輸入整數?

enter codint[] A= new int [10]; 
    int[] B= new int [10]; 
    int[] C= new int [10]; 
    int[] D= new int [10]; 
    int[] E= new int [10]; 
    int counter=0, ran_num1,ran_numb,avg; 
    while(counter<10){ 
     ran_num1= (int)(Math.random()*100 + 1); 
     ran_numb= (int)(Math.random()*100 + 1); 
     A[counter]=ran_num1; 
     B[counter]=ran_numb; 
     C[0]= A[counter]+ B[counter]; 
     D[counter]=B[counter]; 
     E[counter]= A[counter] + B[counter] + C[counter] + D [counter]; 
     counter++;} 
    for(int i=0; i < 10; i++){ 
     System.out.println(D[i]);  }e here 
+3

這樣的:'的System.out.println( 「請輸入一個整數,而不是一個字母」);' – 2015-02-09 22:38:38

+0

代替input.nextInt大概();使用int x = Integer.parseInt(input.next())arraye [j] = x;並拋出一個try catch塊捕捉異常並打印上面的註釋 – 2015-02-09 22:40:00

+0

對不起,如果我有點模糊新這個,但我的意思是,如果程序要求你把10個整數找到平均值,但你把一封信我如何讓它顯示爲一個錯誤,它只是告訴用戶再次嘗試,但這次使用迭代器。 – programmer2015 2015-02-09 22:40:39

回答

0

嗯...我會保持簡單,並用簡單的程序回答「如何從用戶獲取整數輸入」。

基本上......當你掃描儀遇到一些不可接受的輸入時...它會拋出一個java.util.InputMismatchException ...所以只是注意它..然後重試,如果你看到這一點。

import java.util.Scanner; 
import java.util.InputMismatchException 

class GetIntegerInput { 

    public static void main(String args[]) { 
     int iWantThisAsInt = iWillReturnIntFromInput(); 
    } 

    public static int iWillReturnIntFromInput() { 
     Scanner scanner = new Scanner(System.in); 
     System.out.print("Please enter an integer :: "); 
     try { 
      int returnInt = scanner.nextInt(); 
      return returnInt; 
     } 
     catch(InputMismatchException e ) { 
      System.out.println("Sorry. That does not look like an integer, Lets try again."); 
      iWillReturnIntFromInput(); 
     } 
     catch(Exception e ) { 
      System.out.println("Some Other exception... Lets try again."); 
      iWillReturnIntFromInput(); 
     } 

    } 

} 
相關問題