我是新来的,当我试图读取文件时遇到了问题。
这是我的代码
public void openFile()
{
try
{
if(Board.state == Board.STATE.LEVEL1)
{
scan = new Scanner(new File("D://OOP Photos//Map.txt"));
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
try
{
if(Board.state == Board.STATE.LEVEL2)
{
scan = new Scanner(new File("D://OOP Photos//Map1.txt"));
}
}
catch(Exception e)
{
System.out.println("Error loading MAP !!! ");
}
try
{
if(Board.state == Board.STATE.LEVEL3)
{
scan = new Scanner(new File("D://OOP Photos//Map2.txt"));
}
}
catch(Exception e)
{
System.out.println("Error loading MAP !!! ");
}
}
如果我注释掉if语句就可以,但是如果我把它留在那里,它会在下一个方法中抛出NullPointerException
:
public void readFile()
{
while(scan.hasNext())
{
for(int i = 0; i < 10; i++)
{
if(scan.hasNext())
{
Map[i] = scan.next();
}
}
}
}
你能帮帮我吗?
谢谢你:)
答案 0 :(得分:0)
做这样的事情:
public static void main(String args[]) {
String filename;
if(Board.state == Board.STATE.LEVEL1) {
filename = "D://OOP Photos//Map1.txt";
}
else if (Board.state == Board.STATE.LEVEL2) {
filename = "D://OOP Photos//Map2.txt";
}
else if (Board.state == Board.STATE.LEVEL3) {
filename = "D://OOP Photos//Map3.txt";
}
readFile(filename);
}
public void readFile(String filename) {
try {
Scanner scan = new Scanner(new File(filename));
int i = 0;
while(scan.hasNext()) {
Map[i] = scan.next();
i++;
}
}
catch(FileNotFoundException e) {
System.out.println("Error loading MAP !!! ");
}
}
答案 1 :(得分:0)
在每个IF语句之前,只需打印出Board.state
和Board.STATE.LEVELx
的值?这将告诉你为什么你的IF都是假的。或者只是设置断点并检查值。
还可以尝试将IF中的==
更改为.equals()
。
答案 2 :(得分:0)
你的app逻辑让我感到困惑。为什么不使用一个{/ 1}}使用一个try / catch块创建简单的公共扫描程序打开文件(字符串文件路径)方法?
答案 3 :(得分:0)
这是需要考虑的事情:
public static class Board {
// I'm assuming this is what's happening?
public static State state = State.LEVEL1;
public enum State {
LEVEL1("Map.txt"), LEVEL2("Map1.txt"), LEVEL3("Map2.txt");
private final String fileName;
private State(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
}
};
public void openFile() {
if (Board.state == null)
throw new RuntimeException("board state not set");
File file = new File("D:/OOP Photos/", Board.state.getFileName());
try (Scanner scan = new Scanner(file)) {
// do the scanning
} catch (FileNotFoundException fnfe) {
// handle file not found
} catch (Exception e) {
// handle other errors
}
}