这是我得到的错误......
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Maze.Map.readFile(Map.java:60)
at Maze.Map.<init>(Map.java:23)
at Maze.Board.<init>(Board.java:16)
at Maze.Maze.<init>(Maze.java:15)
at Maze.Maze.main(Maze.java:9)
以下是我的代码!
package Maze;
import javax.swing.*;
public class Maze
{
public static void main(String[] args)
{
new Maze();
}
public Maze()
{
JFrame f = new JFrame();
f.setTitle("Maze Game");
f.add(new Board());
f.setSize(464, 485);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
package Maze;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener
{
private Timer timer;
private Map m;
public Board()
{
m = new Map();
timer = new Timer(25, this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
for(int y = 0; y < 14; y++)
{
for(int x = 0; x < 14; x++)
{
if(m.getMap(x, y).equals("g"))
{
g.drawImage(m.getFloor(), x * 32, y * 32, null);
}
if(m.getMap(x, y).equals("w"))
{
g.drawImage(m.getWall(), x * 32, y * 32, null);
}
}
}
}
}
package Maze;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.ImageIcon;
public class Map
{
private Scanner m;
private String Map[] = new String[14];
private Image floor,
wall;
public Map()
{
ImageIcon img = new ImageIcon("C://Test//MazeGame//floor.jpg");
floor = img.getImage();
img = new ImageIcon("C://Test//MazeGame//wall.jpg");
wall = img.getImage();
openFile();
readFile();
closeFile();
}
public Image getFloor()
{
return floor;
}
public Image getWall()
{
return wall;
}
public String getMap(int x, int y)
{
String index = Map[y].substring(x, x + 1);
return index;
}
public void openFile()
{
try
{
m = new Scanner(new File("C://Test//MazeGame//Map.txt"));
}catch(Exception e)
{
System.out.print("Error Loading Map!");
}
}
public void readFile()
{
while(m.hasNext())
{
for(int i = 0; i < 14; i++)
{
Map[i] = m.next();
}
}
}
public void closeFile()
{
m.close();
}
}
答案 0 :(得分:5)
我不知道这是不是你的错误(你没有告诉我们哪一行是你的Map类的第60行,导致你的异常的行),但这是危险的代码:
while(m.hasNext())
{
for(int i = 0; i < 14; i++)
{
Map[i] = m.next();
}
}
您在每次循环迭代时调用hasNext()
,但调用next()
14次!应该存在严格的1对1关联,因为每个next()
应与之前的hasNext()
匹配。
此外,没有理由嵌套for循环,因为while循环将处理您需要的所有内容。你可能会得到类似的东西:
int i = 0;
while(m.hasNext()) {
Map[i] = m.next();
i++;
}
但是使用ArrayList而不是数组会更安全。
顺便说一句,请学习并遵循Java编码惯例。方法和字段/变量/参数都应以小写字母开头,因此不允许使用Map [i],而应该是map [i]。这样做有助于我们更好地理解和遵循您的代码,从而为您提供帮助。