2016-06-09 30 views
0

我有一個問題是,當我輸入值爲數組2d的值有效,一切都完成了,但是當我輸入totalRow或totalColumn變量的錯誤值時,那麼我的輸入函數迫使我輸入double並在第二次獲取值。 這是我的代碼:輸入函數在Java中調用後得到錯誤的值?

public static void input() { 
    Scanner sc = new Scanner(System.in); 
    try { 
     System.out.println("Input total totalRow: "); 
     totalRow = sc.nextInt(); 
     // verify value input must be a positive integer and greater than zero 
     if (totalRow <= 0) { 
      System.out.println("Input value must be a positive integer and greater than zero!"); 
      input(); 
     } 

     System.out.println("Input total totalColumn: "); 
     totalColumn = sc.nextInt(); 
     // verify value input must be a positive integer and greater than zero 
     if (totalRow <= 0) { 
      System.out.println("Input value must be a positive integer and greater than zero!"); 
      input(); 
     } 

     // check case array must be square array 
     if (totalRow != totalColumn) { 
      System.out.println("Array must be square!"); 
      input(); 
     } 
    } catch (InputMismatchException e) { 
     // print message when user input other than integer 
     System.out.println("Please input an integer!"); 
     input(); 
    } 

    // initialize array with totalRow and totalColumn 
    array = new char[totalRow][totalColumn]; 

    // input value for array 
    for (int i = 0; i < totalRow; i++) { 
     for (int j = 0; j < totalColumn; j++) { 
      array[i][j] = sc.next().charAt(0); 
     } 
    } 
} 

例:I輸入2和用於totalRow和totalColumn:消息出現,我重新輸入爲2和2中,但我已經進入1 2 3 4 5 6 7 8對陣列和值從5

+2

你可能不想使用遞歸來重複輸入 –

回答

2

得到你有幾件事情在這裏,正在你的代碼失敗:

  1. 錯字:你正在檢查totalRow <= 0兩次(複製粘貼肯定錯誤)
  2. 如果con那麼你再次呼叫輸入: 這樣做會做一個遞歸實現的方法,這可能會導致不希望的重複序列,瘋狂駕駛用戶和開發者

  3. 你忘記了scanner.nextInt不會消耗您輸入的最後一個換行符

我會建議做類似修改代碼:

if (totalRow <= 0) { 
     System.out.println("Input value must be a positive integer and greater than zero!"); 
     //input(); 
     } 

     System.out.println("Input total totalColumn: "); 
     totalColumn = sc.nextInt(); 
     sc.nextLine(); 
     // verify value input must be a positive integer and greater than 
     // zero 
     if (totalColumn <= 0) { 
     System.out.println("...... 
0

沒有與遞歸algorit問題HM。即使它適用於正確的輸入,但它會反覆要求價值。因爲當你犯了錯誤輸入()函數將從頭開始重新啓動。因此,如果您想更好地使用遞歸,可使用input_Total_Column()input_Total_Row()的單獨函數。 還有一個複製粘貼錯誤。您正在檢查totalColumn < = 0您的代碼中有兩次。
//您的代碼//

`對(INT I = 0;我< totalRow;我++){

for (int j = 0; j < totalColumn; j++) { 

     array[i][j] = sc.next().charAt(0); 

    } 
} 

}`

如果在原始輸入值,這似乎是一個不正確的邏輯。字符串array_input = sc.nextLine(); 使用.split()將字符串分開。字符串使用.split()分隔字符串。函數 然後你可以很容易地使用Integer.parseInt()將相應的字符串值轉換爲整數

相關問題