// here is a sample text file below board.txt
/* 4 4
x t x .
. . s .
x . . .
moves.txt lru
l for left, r for right u for up and d for down.
The first text file argument is a board game file on which s represents a start position and t the target.
and the second text file argument is a moves text file. I want to pass the second argument so that I can make those moves across the board file.
*/
public class VGame {
public static void main(String[] args) {
int m = StdIn.readInt();
int n = StdIn.readInt();
String[][] board1 = new String[m][n];
for (int i = 0; i < board1.length; i++) {
// the condition becomes false then gives access back to the outer for loop
for (int j = 0; j < board1[i].length; j++) {
board1[i][j] = StdIn.readString(); //reading from a text files
}
}
// now let's print a two dimensional array in Java for
/*for (char[] a : board1)
{
for (char i : a)
{
System.out.print(i + " ");
} System.out.println("\n");
} */
StdOut.println(m + " " + n);
for (int i = 0; i < board1.length; i++)
{
for (int j = 0; j < board1[i].length; j++)
{
System.out.print(" "+ board1[i][j]);
}
System.out.println();
}
// printing 2D array using Arrays.deepToString() method
//System.out.println("another way to print 2D arrays");
//System.out.println(Arrays.deepToString(board1));
StdOut.println(args[0]);
}
}
这应将索引读为Integer,然后逐行读取String。
public class Main {
public static void main(String[] args) {
int m = 0;
int n = 0;
Scanner s = new Scanner(System.in);
System.out.print("input m: ");
m = s.nextInt();
System.out.print("input n: ");
n = s.nextInt();
String[][] board1 = new String[m][n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print("input string: ");
board1[i][j] = s.nextLine();
}
}
s.close();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.println(board1[i][j]);
}
}
}
}