如何在java中输入字符数组?

时间:2016-08-12 13:34:04

标签: java arrays

我有一个像下面的二维数组

---
-m-
p--

如何将这些输入数组而不仅仅是? 我知道nextInt(),nextLine()但是这些问题对我没有帮助吗?

这是我的代码

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    char[][] board = new char[n][n];
    for(int i=0 ; i<n ; i++){
        for(int j=0 ; j<n ;j++){
            board[i][j] = //problem at here

        }
    }

2 个答案:

答案 0 :(得分:0)

如果您使用nextLine(),则可以使用charAt(index)获取每个字符。

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    char[][] board = new char[n][n];
    for(int i=0 ; i<n ; i++){
        String line = in.nextLine();
        for(int j=0 ; j<n ;j++){
            board[i][j] = line.charAt(j);
    }
}

答案 1 :(得分:0)

我假设你要求一个字符数组,在这种情况下你有部分解决方案,但不是整个问题。

关键是使用nextLine()获取一行,然后使用循环获取每个char并将其存储在数组中(我们将假设这些行具有固定长度事情实施)。

我将跳过查找文件中行数的工作,我将留给您。

/* used to set the size of the 2d array*/
FileReader reader = new FileReader("filename");
BufferedReader bReader = new BufferedReader(reader);
int numLines = getNumLines(file);
int lineLength = getLengthLines(file); 

char[][] map = new char[numLines][lineLength]
for(int i = 0; i<numLines; i++){
    String currentLine = bReader.nextLine();
    for(int x = 0; x<lineLength; i++)
        map[i][x] = currentLine.charAt(x);
    }
}

如果您有任何其他问题,请务必发表评论!

Java中reading in a file的引用。