我试图获得扫描仪功能,以从文本文件中读取每个元素,并将其放置在2d数组中。我正在使用Java上的扫描器函数,并使用for和while循环将这些项作为char变量放置在数组中。
我正在使用的示例txt文件为.brd格式,并且为:
format 1
......
.C..D.
..BA..
......
我已经尝试过使用Scanner.next(),scanner.nextByte()和Scanner.next()。chatAt(i),这是我最接近解决它的方法。但是当我使用它时。我是当前行的索引。但是,与其遍历和扫描其中的每个元素,不如对角线下降。
我当前的代码是 i和j是文件中第一行以外的行和列的数量。
try {
reader = new Scanner(new File(file));
} catch (FileNotFoundException ex){
Logger.getLogger(InputReader.class.getName()).log(Level.SEVERE, null, ex);
}
s = reader.nextLine();
char gridE;
String[][] grid = new String[rows][length];
int j =0;
while (reader.hasNextLine()) {
for(int i = 0; i < length;i++){
gridE = reader.next().charAt(i);
String b = "5";
if(gridE == '.'){
grid[i][j] = "blank";
} else if(gridE == 'A' || gridE == 'B' || gridE == 'C' || gridE == 'D'){
grid[i][j] = "Robot";
} else if(gridE == '+'){
grid[i][j] = "Gear";
} else if(gridE == '-') {
grid[i][j] = "Gear";
} else if(gridE == '1') {
grid[i][j] = "Flag1";
} else if(gridE == '2') {
grid[i][j] = "Flag2";
} else if(gridE == '3') {
grid[i][j] = "Flag3";
} else if(gridE == '4') {
grid[i][j] = "Flag4";
} else if(gridE == 'x') {
grid[i][j] = "Pit";
} else if(gridE == 'v') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == '>') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == '<') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == '^') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == 'N') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == 'n') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == 'S') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == 's') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == 'W') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == 'w') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == 'E') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == 'e') {
grid[i][j] = "ConveyorBelt";
} else if(gridE == '[') {
grid[i][j] = "LaserEmitter";
} else if(gridE == ']') {
grid[i][j] = "LaserReciever";
} else if(gridE == '(') {
grid[i][j] = "LaserReciever";
} else if(gridE == ')') {
grid[i][j] = "LaserRecieve";
}
}
j++;
}
我希望它遍历行中的每个元素(仅由一个字符组成,例如仅包含“。”),然后将其添加到2d数组中,并带有正确的if语句。它可以正确地添加到数组中,但只对角地做元素。
答案 0 :(得分:1)
为了正确地声明和初始化数组,您需要知道该数组中将驻留多少个元素。对于2D数组,您将需要知道该数组中需要初始化多少行(字符串[行] [])。 2D阵列中的每一行可以有任意数量的列,例如:
/* A 4 Row 2D String Array with multiple
number of columns in each row. */
String[][] myArray = {
{"1", "2", "3"},
{"1", "2", "3", "4", "5"},
{"1"},
{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}
};
要获取行数,您需要设置数组,您需要对文件进行传递以计算有效数据行(行)的数量,以便初始化2D像这样的数组,
String file = "File.txt";
String[][] myArray = null;
try {
// Get number of actual data rows in file...
Scanner reader = new Scanner(new File(file));
reader.nextLine(); // Read Past Header Line
int i = 0;
while (reader.hasNextLine()) {
String fileLine = reader.nextLine().trim();
// Ignore Blank Lines (if any)
if (fileLine.equals("")) {
continue;
}
i++;
}
// Initialize the Array
myArray = new String[i][];
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
现在,您可以重新读取文件并根据需要填充数组,例如,以下是初始化和填充名为 myArray 的2D字符串数组的完整代码:
String file = "File.txt";
String[][] myArray = null;
try {
// Get number of actual data rows in file...
Scanner reader = new Scanner(new File(file));
reader.nextLine(); // Read Past Header Line
int i = 0;
while (reader.hasNextLine()) {
String fileLine = reader.nextLine().trim();
// Ignore Blank Lines (if any)
if (fileLine.equals("")) {
continue;
}
i++;
}
// Initialize the Array
myArray = new String[i][];
// Re-Read file and fill the 2D Array...
i = 0;
reader = new Scanner(new File(file));
reader.nextLine(); // Read Past Header Line
while (reader.hasNextLine()) {
String fileLine = reader.nextLine().trim();
// Ignore Blank Lines (if sny)
if (fileLine.equals("")) {
continue;
}
// Slpit the read in line to a String Array of characters
String[] lineChars = fileLine.split("");
/* Iterate through the characters array and translate them...
Because so many characters can translate to the same thing
we use RegEx with the String#matches() method. */
for (int j = 0; j < lineChars.length; j++) {
// Blank
if (lineChars[j].matches("[\\.]")) {
lineChars[j] = "blank";
}
// Robot
else if (lineChars[j].matches("[ABCD]")) {
lineChars[j] = "Robot";
}
// Gear
else if (lineChars[j].matches("[\\+\\-]")) {
lineChars[j] = "Gear";
}
// FlagN
else if (lineChars[j].matches("[1-4]")) {
lineChars[j] = "Flag" + lineChars[j];
}
// Pit
else if (lineChars[j].matches("[x]")) {
lineChars[j] = "Pit";
}
// ConveyotBelt
else if (lineChars[j].matches("[v\\<\\>\\^NnSsWwEe]")) {
lineChars[j] = "ConveyorBelt";
}
// LaserEmitter
else if (lineChars[j].matches("[\\[]")) {
lineChars[j] = "LaserEmitter";
}
// LaserReciever
else if (lineChars[j].matches("[\\]\\(\\)]")) {
lineChars[j] = "LaserReciever";
}
// ............................................
// ... whatever other translations you want ...
// ............................................
// A non-translatable character detected.
else {
lineChars[j] = "UNKNOWN";
}
}
myArray[i] = lineChars;
i++;
}
reader.close(); // We're Done - close the Scanner Reader
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
如果要在控制台窗口中显示2D阵列的内容,则可以执行以下操作:
// Display the 2D Array in Console...
StringBuilder sb;
for (int i = 0; i < myArray.length; i++) {
sb = new StringBuilder();
sb.append("Line ").append(String.valueOf((i+1))).append(" Contains ").
append(myArray[i].length).append(" Columns Of Data.").
append(System.lineSeparator());
sb.append(String.join("", Collections.nCopies((sb.toString().length()-2), "="))).
append(System.lineSeparator());
for (int j = 0; j < myArray[i].length; j++) {
sb.append("Column ").append(String.valueOf((j+1))).append(": -->\t").
append(myArray[i][j]).append(System.lineSeparator());
}
System.out.println(sb.toString());
}
将文件数据放入ArrayList中以创建2D阵列:
但是,将数据文件读入ArrayList会使事情变得更加容易,因为ArrayList或List Interface可以根据需要动态增长,并且您只需要读取一次文件。所需数组的大小可以由ArrayList的大小确定。这是一个除了使用ArrayList以外,执行与上述相同的操作的示例:
String file = "File.txt";
String[][] myArray = null;
ArrayList<String> dataList = new ArrayList<>();
try {
// Get number of actual data rows in file...
Scanner reader = new Scanner(new File(file));
reader.nextLine(); // Read Past Header Line
while (reader.hasNextLine()) {
String fileLine = reader.nextLine().trim();
// Ignore Blank Lines (if any)
if (fileLine.equals("")) {
continue;
}
dataList.add(fileLine); // Add data line to List
}
reader.close(); // Close the Scanner Reader - Don't need anymore
}
catch (FileNotFoundException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
// Initialize the Array
myArray = new String[dataList.size()][];
// Iterate through the ArrayList and retrieve the data
for (int i = 0; i < dataList.size(); i++) {
String dataLine = dataList.get(i).trim();
// Split the data line into a String Array of characters
String[] lineChars = dataLine.split("");
/* Iterate through the characters array and translate them...
Because so many characters can translate to the same thing
we use RegEx with the String#matches() method. */
for (int j = 0; j < lineChars.length; j++) {
// Blank
if (lineChars[j].matches("[\\.]")) {
lineChars[j] = "blank";
}
// Robot
else if (lineChars[j].matches("[ABCD]")) {
lineChars[j] = "Robot";
}
// Gear
else if (lineChars[j].matches("[\\+\\-]")) {
lineChars[j] = "Gear";
}
// FlagN
else if (lineChars[j].matches("[1-4]")) {
lineChars[j] = "Flag" + lineChars[j];
}
// Pit
else if (lineChars[j].matches("[x]")) {
lineChars[j] = "Pit";
}
// ConveyotBelt
else if (lineChars[j].matches("[v\\<\\>\\^NnSsWwEe]")) {
lineChars[j] = "ConveyorBelt";
}
// LaserEmitter
else if (lineChars[j].matches("[\\[]")) {
lineChars[j] = "LaserEmitter";
}
// LaserReciever
else if (lineChars[j].matches("[\\]\\(\\)]")) {
lineChars[j] = "LaserReciever";
}
// ............................................
// ... whatever other translations you want ...
// ............................................
// A non-translatable character detected.
else {
lineChars[j] = "UNKNOWN";
}
}
myArray[i] = lineChars;
}