2017-01-25 7 views
1

ファイルからサンプル入力を読み込んで2D配列に挿入する必要がある課題に取り組んでいます。入力の例を次に示します。値を読み込んで2次元配列に挿入する

5 6 
1 3 4 B 4 3 
0 3 5 0 0 9 
0 5 3 5 0 2 
4 3 4 0 0 4 
0 2 9 S 2 1 

5と6は配列の次元です。ユーザーはこのような多くの配列を一度に入力できなければなりません。ユーザーが-1を入力するとプログラムは終了します。

public static void main (String[] args){ 
    Scanner sc = new Scanner(System.in); 
    int arHeight = sc.nextInt(); 
    int arWidth = sc.nextInt(); 
    sc.useDelimiter(" "); 
    String[][] map = new String[arHeight][arWidth]; 

     for(int i=0; i<arHeight; i++){ 
      for(int j=0; j<arWidth; j++){ 
       map[i][j] = sc.nextLine(); 
      }//end inner for 
     }//end outter for 

      for(int i=0; i<arHeight; i++){ 
      for(int j=0; j<arWidth; j++){ 
       System.out.print(map[i][j] + " "); 
      }//end inner for 
     }//end outter for 
    } 

私は再帰を使用し、そのことはできません割り当て状態:これは、(私は配列は、コードの動作を確認するためにプリントアウト)する必要がありとして動作していないようです、私がこれまで持っているコードです。 2D配列を使用する必要があります。私は他の質問を見てきましたが、まだそれを理解していないようです。 助けてくれてありがとう!あなたは私はj回に

for(int i=0; i<arHeight; i++){ 
     for(int j=0; j<arWidth; j++){ 
      map[i][j] = sc.nextLine(); 

を*行全体を読んで

+0

ようこそスタックオーバーフロー!宿題の助けを求めているようです。それ自体に問題はありませんが、これらのことを守ってください(http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions/338845#338845)、それに応じて質問を編集してください。 –

+0

ありがとうございます。 – Gabbie

答えて

2

また、あなたは、文字列配列内のデータアルを維持し、私は理由を知りません。ここでは解決策は以下のとおりです。

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    int arHeight = sc.nextInt(); 
    int arWidth = sc.nextInt(); 

    int[][] map = new int[arHeight][arWidth]; 

    for(int i=0; i<arHeight; i++){ 
     for(int j=0; j<arWidth; j++){ 
      map[i][j] = sc.nextInt(); 
     }//end inner for 
    }//end outter for 

    for(int i=0; i<arHeight; i++){ 
     for(int j=0; j<arWidth; j++){ 
      System.out.print(map[i][j] + " "); 
     }//end inner for 
    } 

} 

その後

char[][] map = new char[arHeight][arWidth]; 

とループの中に使用するようにしてください:

if(sc.next().charAt(0) != " ") map[i][j] =sc.next().charAt(0); 

あなたが「」ではないすべての文字を読んでください。この道を。

+0

配列に2つの文字があるため、文字列配列を使用しました。BとSです。文字配列が最適に機能しますか? – Gabbie

+0

回答を更新します。私はあなたがcharsを持っていることを観察しなかった –

+0

ありがとう、私は助けてくれてありがとう!今は正常に動作しているようです! – Gabbie

関連する問題