2017-01-25 104 views
1

我正在做一个分配,我需要从文件中读取样本输入并将其插入到二维数组中。以下是一个输入示例:读取值插入二维数组

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 
    } 

的分配状态,我不能使用递归和我必须使用二维数组。我已经看过其他问题,但似乎无法弄清楚。 感谢您的帮助!

+0

欢迎来到Stack Overflow!看起来你正在寻求作业帮助。虽然我们本身没有任何问题,但请观察这些[应做和不应该](http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions/338845#338845),并相应地编辑您的问题。 –

+0

谢谢,我马上就明白:) – Gabbie

回答

2

你读了整条生产线我*进行j次

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

也是你保持人在一个字符串数组中的数据,我不知道为什么。这里是解决方案:

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]; 

,并在for循环:

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

这样,你应该阅读所有这些都没有的 “字符”。

+0

我曾经使用过一个字符串数组,因为数组中有两个字符,B和S.会不会有一个字符数组最好? – Gabbie

+0

我会更新答案。我没有注意到你有字符 –

+0

谢谢,我感谢帮助!它现在似乎正在工作! – Gabbie