-2

我对java很陌生,并且有以下文本文件我想变成一个迷宫:

*************************************************
*************************************************
*************************************************
************************S************************
*******************      *F    ******************
****************   * * *******    ***************
**************    *         * ***   *************
*************  *                 **   ***********
************  *    **    *         **  **********
**********   *      *   ***      **     *********
**********          **         **     *   *******
***************       **     **     *****  ******
*****************       ** **      ******* ******
******************        *  *   *********  *****
******* ************         * ************ *****
******      ********** *    * **********     ****
******  **    ********  *  * ********        ****
*****  ***      *******  *   ******    * ***  ***
*****  ** *       ****** *  ******     * ***  ***
****   ** *     ******** *  ********   *  **  ***
****   ** *    ** *******  ******* ** * * **   **
****  ** * *** **  ******  ******  **  *   *   **
****  **  * *  **********  ********** *** ***  **
****  *** **** ********* *  ********* **  ***  **
**** ****  ***  *******      *******  ** ****  **
**** ***** ***   ******       *****  *   ***** **
****  ****  * *    **               *** *****  **
****  ** **   ** *     *     *     * * ***** * **
****  *******     * * ********* * *   ** ****  **
**** ***** *****   * * * *** ***  ****** ***   **
****  ** **   *******   *** *  ******* **** * ***
*****  ***** * * ********* ***** **  * ****** ***
*****  **  *** *  *  **********   *  * * **   ***
****** ** * ** *  *  *   **   *   *  *** **  ****
******  ***  ***  *  *        ** ** *** ***  ****
******   ** *  ***** *    *    * ****   **  *****
*******   *** * ** ****   *   **** ** ***  ******
********   **** *  * **********   * ***   *******
*********   ****  *     *       * * *** *********
**********    *****  *        * ******  *********
*********** *    ***** ** ** ********** *********
************  **   **************  ** ***********
**************** *               **  ************
**************** *******      **** **************
******************  ****** ****  ****************
*************************************************
*************************************************
*************************************************
*************************************************
*************************************************

问题是我每次尝试上传文件时都会收到“文件错误”消息(从第 202 行开始)。这是我的主要程序:

/*
 * MazeRunner.java
 *
 */
package mazerunner;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.Timer;
import javax.swing.JFileChooser;
import javax.swing.JPanel;

public class MazeRunner extends javax.swing.JFrame {

    public static final int wall = 0;
    public static final int open = 1;
    public static final int visited = 2;
    public static final int onpath = 3;
    public static final int start = 4;
    public static final int end = 5;
    public static final int pending = 6;
    public static final int mazeSize = 50;
    public static Color[] colors = {Color.BLACK, Color.WHITE, Color.MAGENTA, Color.ORANGE,
        Color.CYAN, Color.RED, Color.LIGHT_GRAY};
    JFileChooser fileChooser = new JFileChooser();
    public int maze[][] = new int[mazeSize][mazeSize];
    public Timer clock = new Timer(100, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tick();
            mazePanel.repaint();
        }
    });

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MazeRunner().setVisible(true);
            }
        });
    }

    public class MyPanel extends JPanel {

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            for (int i = 0; i < mazeSize; i++) {
                for (int j = 0; j < mazeSize; j++) {
                    g.setColor(colors[maze[i][j]]);
                    g.fillRect(i, j, 12, 12);
                }
            }
        }
    }

    public MazeRunner() {
        initComponents();
        clock.start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        mazePanel = new MyPanel();
        loadMaze = new javax.swing.JButton();
        collectionSelection = new javax.swing.JComboBox();
        title = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        mazePanel.setBackground(new java.awt.Color(204, 255, 204));
        mazePanel.setPreferredSize(new java.awt.Dimension(600, 600));

        org.jdesktop.layout.GroupLayout mazePanelLayout = new org.jdesktop.layout.GroupLayout(mazePanel);
        mazePanel.setLayout(mazePanelLayout);
        mazePanelLayout.setHorizontalGroup(
            mazePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 600, Short.MAX_VALUE)
        );
        mazePanelLayout.setVerticalGroup(
            mazePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 600, Short.MAX_VALUE)
        );

        loadMaze.setText("Load File");
        loadMaze.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadMazeActionPerformed(evt);
            }
        });

        collectionSelection.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Stack", "Queue" }));

        title.setText("No File Loaded");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(mazePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(54, 54, 54)
                        .add(title, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 351, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .add(28, 28, 28)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(loadMaze, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(46, 46, 46))
                    .add(layout.createSequentialGroup()
                        .add(collectionSelection, 0, 111, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(loadMaze)
                        .add(81, 81, 81)
                        .add(collectionSelection, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(title, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 25, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(mazePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void loadMazeActionPerformed(java.awt.event.ActionEvent evt) {                                         

        int retval = fileChooser.showOpenDialog(this);
        if (retval == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                String s;
                while ((s = reader.readLine()) != null) {
                    for (int i = 0; i < mazeSize; i++) {
                        for (int j = 0; j < mazeSize; j++) {


                            if (s.charAt(j) == '*') {
                                maze[i][j] = wall;
                            }
                            if (s.charAt(j) == ' ') {
                                maze[i][j] = open;
                            }
                            if (s.charAt(j) == 'F') {
                                maze[i][j] = end;
                            }
                            if (s.charAt(j) == 'S') {
                                maze[i][j] = start;
                            } else {
                                maze[i][j] = wall;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                title.setText("File Error");
            }
        }

    }                                        
    // Variables declaration - do not modify                     
    private javax.swing.JComboBox collectionSelection;
    private javax.swing.JButton loadMaze;
    private javax.swing.JPanel mazePanel;
    private javax.swing.JLabel title;
    // End of variables declaration                   
}

我认为问题出在这个代码段上,但无论我如何愚弄它,我都无法让它工作:

private void loadMazeActionPerformed(java.awt.event.ActionEvent evt) {                                         

            int retval = fileChooser.showOpenDialog(this);
            if (retval == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    BufferedReader reader = new BufferedReader(new FileReader(file));
                    String s;
                    while ((s = reader.readLine()) != null) {
                        for (int i = 0; i < mazeSize; i++) {
                            for (int j = 0; j < mazeSize; j++) {


                                if (s.charAt(j) == '*') {
                                    maze[i][j] = wall;
                                }
                                if (s.charAt(j) == ' ') {
                                    maze[i][j] = open;
                                }
                                if (s.charAt(j) == 'F') {
                                    maze[i][j] = end;
                                }
                                if (s.charAt(j) == 'S') {
                                    maze[i][j] = start;
                                } else {
                                    maze[i][j] = wall;
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    title.setText("File Error");
                }
            }

        }

这是生成的堆栈跟踪:

java.lang.StringIndexOutOfBoundsException: String index out of range: 49
    at java.lang.String.charAt(String.java:686)
    at mazerunner.MazeRunner.loadMazeActionPerformed(MazeRunner.java:172)
    at mazerunner.MazeRunner.access$100(MazeRunner.java:19)
    at mazerunner.MazeRunner$3.actionPerformed(MazeRunner.java:111)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6382)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
    at java.awt.Component.processEvent(Component.java:6147)
    at java.awt.Container.processEvent(Container.java:2083)
    at java.awt.Component.dispatchEventImpl(Component.java:4744)
    at java.awt.Container.dispatchEventImpl(Container.java:2141)
    at java.awt.Component.dispatchEvent(Component.java:4572)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
    at java.awt.Container.dispatchEventImpl(Container.java:2127)
    at java.awt.Window.dispatchEventImpl(Window.java:2489)
    at java.awt.Component.dispatchEvent(Component.java:4572)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:704)
    at java.awt.EventQueue.access$400(EventQueue.java:82)
    at java.awt.EventQueue$2.run(EventQueue.java:663)
    at java.awt.EventQueue$2.run(EventQueue.java:661)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:677)
    at java.awt.EventQueue$3.run(EventQueue.java:675)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:674)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)  

如果有人能指出我正确的方向,将不胜感激!

4

3 回答 3

2

问题是你的迷宫大小实际上不是 50。首先,因为你从 0 开始计数,它需要比实际值小一。其次,您提供的文件的每一行中只有 49 个字符。只需将 mazesize 更改为 48 即可。您可能希望努力使您的代码更易于阅读。

于 2013-03-09T23:07:39.230 回答
2

问题出现在这一行:

if (s.charAt(j) == '*')

该错误告诉您索引 ( j) 大于 ( ) 中的字符Strings。所以看看你如何设置的值j

for (int j = 0; j < mazeSize; j++)

我们可以推断mazeSize大于 的长度s。您应该为循环找出不同的结束条件。

ps我建议你学习如何调试自己的代码,这样你就可以自己发现这些问题。您的代码还有其他问题,我不会在这里讨论。System.out.println()通过在代码中添加语句或使用 IDE 中的调试器,您将在解决这些问题方面取得一些进展。

于 2013-03-09T23:08:32.440 回答
0

如前所述,问题来自文件的每一行不包含 50 个但 49 个(或 48 个)字符的事实。IMO 没有必要这样做,for-statement因为您已经在使用这行代码为代表迷宫的文件的每一行读取一个字符串:

String s;
while ((s = reader.readLine()) != null) {

所以你只需要在这里做一个 for 语句,而不必随意选择你的字符串的大小,而是:

for(int i = 0 ; i < s.length() ; i++) {
    if(s.charAt(i) == '*') {
        // etc...

所以最后你的陈述将是:

String s;

while ((s = reader.readLine()) != null) 
{
    for(int i = 0 ; i < s.length() ; i++) 
    {
        if(s.charAt(i) == '*') { maze[i][j] = wall; }
        if(s.charAt(j) == ' ') { maze[i][j] = open; }
        if(s.charAt(j) == 'F') { maze[i][j] = end; }
        if(s.charAt(j) == 'S') { maze[i][j] = start; } 
        else { maze[i][j] = wall; }
    }
}
于 2013-03-09T23:14:33.037 回答