2016-10-14 7 views
0

ユーザ入力の文字列を使用してJavaで2次元配列を作成しようとしています。私はすでに文字列を取得しており、配列の作成方法を理解しています。私はちょうど配列に値を取得する方法を考え出すのに問題があります。あなたが疑問に思っている場合は、はい、私は配列を使用する必要があります。ここで私はこれまで持っているものです。ユーザ入力を使用してJavaで2D配列を生成する方法は?

private static int[][] parseTwoDimension(String strInput) 
     { 
      int rows = 0; //number of rows in the string 

      for (int i = 0; i < strInput.length(); i++) 
      { 
       if (strInput.charAt(i) == '!') //the ! is an indicator of a new row 
       { 
        rows++; 
       } 
      } 

      int[][] arr = new int[rows][]; //create an array with an unknown number of columns 
      int elementCounter = 0; //keep track of number of elements 
      int arrayIndexCounter = 0; //keep track of array index 

      for (int i = 0; i < strInput.length(); i++) 
      { 
       if (strInput.charAt(i) != '!') //while not the end of the row 
       { 
        elementCounter++; //increase the element count by one 
       } 
       else //reached the end of the row 
       { 
        arr[arrayIndexCounter] = new int[elementCounter]; //create a new column at the specified row 
        elementCounter = 0; //reset the element counter for the next row 
        arrayIndexCounter++; //increase the array index by one 
       } 
      } 
     /* 
     This is where I need the help to populate the array 
     */ 
     char c; //each character in the string 
     int stringIndex = -1; //keep track of the index in the string 
     int num; //the number to add to the array 
     for (int i = 0; i < arr.length; i++) 
     { 
      for (int j = 0; j < arr[i].length; j++) 
      { 
       stringIndex++; //increment string index for next element 
       c = strInput.charAt(stringIndex); //the character at stringIndex 
       if (c == '!') //if it is the end of the row, do nothing 
       { 

       } 
       else //if it is not the end of the row... 
       { 
        String s = Character.toString(c); //convert character to String 
        num = Integer.parseInt(s); //convert String to Integer 
        arr[i][j] = num; //add Integer to array 
       } 
      } 
     } 
     return arr; //return a two dimensional array the user defined 
    } 

すべてのヘルプは大歓迎です:)

答えて

2

私はあなたのコードを編集し、以下のことを掲載しました。

  1. 文字列を区切り文字 '!'で区切るには、string.split( "!")を使用します。これは、その後、アレイ

  2. を返し、

個々の文字に文字列を分離するために( "")のstring.Splitを使用するコードは以下の投稿:

private static int[][] parseTwoDimension(String strInput) 
{ 
    String[] rows = strInput.split("!");  
    int[][] arr = new int[rows.length()][]; 

    for(int i = 0; i < rows.length; i++) 
    { 
     String[] elements = rows[i].split(""); 
     int[] intElements = new int[elements.length]; 

     for(int j = 0; j < elements.length; j++) 
     { 
      intElements[j] = Integer.parseInt(elements[j]); 
     } 
     arr[i] = intElements; 
    } 
} 

が、この作品なら、私を知ってみましょう。 string.split()関数は、Stringsを配列に解析するときに本当に便利です。

+0

これは完全に機能しました。ありがとう!私もstring.split()を使用するとは思わなかった – Ethan

関連する問題