我是Java新手,对此有麻烦。我需要制作两个不同的程序。一个制作txt文件,另一个制作。第一个程序使网格。 2在方法中读取txt,然后我应该在主要调用它。我似乎无法弄清楚。
初始数组(txt.file):
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
import java.util.Collections;
public class Grid {
public static void main(String[] args) {
ArrayList<Integer> indNum = new ArrayList<Integer>();
ArrayList<Integer> elemNum = (ArrayList<Integer>) indNum.clone();
ranNum(indNum);
ranNum(elemNum);
String grid[][] = mGrid();
replaceGrid(grid, indNum.get(0), elemNum.get(0));
replaceGrid(grid, indNum.get(1), elemNum.get(1));
replaceGrid(grid, indNum.get(2), elemNum.get(2));
disGrid(grid);
}
public static String[][] mGrid() {
String[][] Array = { { " *", " *", " *", " *", " *" },
{ " *", " *", " *", " *", " *" },
{ " *", " *", " *", " *", " *" },
{ " *", " *", " *", " *", " *" },
{ " *", " *", " *", " *", " *" }
};
return Array;
}
public static void disGrid(String[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
}
public static ArrayList<Integer> ranNum(ArrayList<Integer> ran) {
for (int i = 0; i < 5; i++) {
ran.add((i));
}
Collections.shuffle(ran);
ran.remove(4);
ran.remove(3);
return ran;
}
public static String[][] replaceGrid(String[][] array, int num1, int num2) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
array[num1][num2] = " O";
}
}
return array;
}
}
输出:
O * * * *
* * * * *
* * * * *
* * O * *
* * * O *
三个O随机放置在网格中 第二部分通过执行数组读取并显示:
package Execute;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
import java.util.Collections;
import java.io.*;
public class part2 {
public static void main(String[] args) {
ArrayList<String> makeGrid= new ArrayList<String>();
readFile(makeGrid);
System.out.print(makeGrid);
}
public static void readFile(ArrayList<String> exec) {
try {
Scanner reader = new Scanner(new File("Grid.txt"));
do {
exec.add(reader.nextLine());
}while (reader.hasNext());
} catch (FileNotFoundException fnf) {
System.out.println("File was not found");
}
}
}
当我运行它时,它不会存储并显示旧网格。相反,它只是打印出我在一行中编写的整个代码。我该如何执行代码并将其存储在arraylist中,以便对其进行操作?
答案 0 :(得分:1)
首先,您需要while (reader.hasNextLine())
如果希望将数组列表显示为多行,则可以手动添加换行符
exec.add(reader.nextLine() + "\n");
或者您实际上可以打印每一行,而不是仅打印arraylist
readFile(makeGrid);
for (String line : makeGrid) {
System.out.println(line);
}
顺便说一句,不建议将可变集合作为参数传递给方法。您应该从return
readFile()
新建一个数组列表