我似乎无法在代码中找到问题,并且想知道您在这里的好人是否愿意帮助我。我的教授要求我们根据从她提供给我们的文件中提取的信息来创建二维数组。使用Scanner和File类,我们应该能够完成此任务,但是,我遇到了一个减速的问题。我的扫描程序无法识别我为它设置的定界符后的整数。这是她提供给我们的文件。
5x7
o,2,3
7,1,3
7,1,1
X,4,2
此信息用换行符分隔,其中块引用中有空格。
这是我的代码:
import java.io.*;
import java.util.*;
public class Battlefield {
// Use the FILL_CHAR for a space that contains no creature.
// Use these chars for creatures so that your code will pass
// the tests used for evaluating your program.
public final char FILL_CHAR = '-';
public final char OGRE = 'o';
public final char CENTAUR = '7';
public final char DRAGON = 'X';
private char[][] field;
public Battlefield(String fn) {
try {
// You write code here.
// Read a file and initialize the field.
// The name of the file is passed in from the driver.
// Keep all the file reading stuff in the try/catch block
// to make file exceptions easier to deal with.
File battlefield = new File(fn);
Scanner scan = new Scanner(battlefield);
scan.useDelimiter("x");
int row = scan.nextInt();
System.out.println(row);
System.out.println(scan.next());
System.out.println(scan.hasNextInt());
int column = scan.nextInt();
char[][] field = new char[row][column];
/**
Scanner scan2 = new Scanner(battlefield);
scan2.useDelimiter(",");
/**
field[scan2.nextInt()][scan2.nextInt()] = OGRE;
field[scan2.nextInt()][scan2.nextInt()] = CENTAUR;
field[scan2.nextInt()][scan2.nextInt()] = CENTAUR;
field[scan2.nextInt()][scan2.nextInt()] = DRAGON;
**/
} catch (IOException ex) {
System.err.println(ex.getStackTrace());
}
}
还有我的主要方法/驱动程序类:
public class BattlefieldDrv {
public static void main(String[] args)
{
Battlefield battlefieldOne = new Battlefield("1field.dat");
System.out.println(battlefieldOne.toString());
}
}
这是我的堆栈跟踪:
> 5
7
o,2,3
7,1,3
7,1,1
X,4,2
false
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at Battlefield.<init>(Battlefield.java:38)
at BattlefieldDrv.main(BattlefieldDrv.java:15)
感谢您的帮助或见解!
答案 0 :(得分:0)
所以让我们逐步看一下这段代码。
scan.useDelimiter("x");
int row = scan.nextInt();
5被读入row
。
System.out.println(row);
5已打印。
System.out.println(scan.next());
读取并打印文件的其余部分,因为这就是x
之后的内容。
System.out.println(scan.hasNextInt());
没有什么可读书的了,所以NoSuchElementException
被扔到了这里。
您需要使扫描仪还接受换行符作为分隔符;您可以使用
scan.useDelimiter("(x|\\s)");
(\\s
是“任何空白”的模式。)
请注意,使用try-with-resources
-construct是一个好习惯:
try (Scanner scan = new Scanner(Paths.get("1field.dat"))) {
scan.useDelimiter(...);
...
} catch (IOException e) {
这将导致您的文件资源自动关闭。