Conway's game of life problems - java
This is the code I was given for my assignment. The task is to find what is wrong with the code. The code is supposed to implement "Conway's Game of Life" : http://en.wikipedia.org/wiki/Conway's_Game_of_Life I can't find where the error is.
import java.util.Scanner;
import javax.swing.JFrame;
public class GameOfLife {
public static void main(String[] args) {
final int testCase = 1;
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setTitle("Conway's Game of Life");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Cell[][] universe = new Cell[100][100];
for (int x = 0; x < universe.length-1; x++) {
for (int y = 0; y < universe[x].length-1; y++) {
universe[x][y] = new Cell();
}
}
if (testCase == 1) {
universe[3][2].calculateNext(3);
universe[3][2].updateCurrent();
universe[3][3].calculateNext(3);
universe[3][3].updateCurrent();
universe[3][4].calculateNext(3);
universe[3][4].updateCurrent();
} else if (testCase == 2) {
universe[49][50].calculateNext(3);
universe[49][50].updateCurrent();
universe[49][51].calculateNext(3);
universe[49][51].updateCurrent();
universe[50][49].calculateNext(3);
universe[50][49].updateCurrent();
universe[50][50].calculateNext(3);
universe[50][50].updateCurrent();
universe[51][50].calculateNext(3);
universe[51][50].updateCurrent();
} else {
}
UniverseComponent component = new UniverseComponent(universe);
frame.add(component);
frame.setVisible(true);
Scanner in = new Scanner(System.in);
String input = in.nextLine();
while (input.length() == 0) {
int neighborCount = 0;
for (int x=1; x<universe.length-2; x++) {
for (int y=1; y<universe[x].length-2; y++) {
neighborCount = 0;
if (universe[x-1][y-1].isAlive()) {
neighborCount++;
}
if (universe[x-1][y].isAlive()) {
neighborCount++;
}
if (universe[x-1][y+1].isAlive()) {
neighborCount++;
}
if (universe[x][y-1].isAlive()) {
neighborCount++;
}
if (universe[x][y+1].isAlive()) {
neighborCount++;
}
if (universe[x+1][y-1].isAlive()) {
neighborCount++;
}
if (universe[x+1][y].isAlive()) {
neighborCount++;
}
if (universe[x+1][y+1].isAlive()) {
neighborCount++;
}
universe[x][y].calculateNext(neighborCount);
}
}
for (int x=1; x<universe.length-2; x++) {
for (int y=1; y<universe[x].length-2; y++) {
universe[x][y].updateCurrent();
}
}
component.repaint();
input = in.nextLine();
}
in.close();
}
I'm not going to do your assignment for you (find the error). But here's a strategy:
Does the code compile? If not, fix that.
Does the program crash when it runs? If so, look at the stack trace for clues. Then use the debugger.
If the program runs without crashing but doesn't advance the game properly, try a simple Game of Life configuration for which you can calculate the expected results by hand and look for where the code behaves differently.
For steps 2 and 3, it's important that you master the basics of using a debugger. Good luck.
Related
Passing Values from Constructor to a Method
My project requires me to make a game where two space ships move around on a game board. I'm not too sure on how to get my X and Y position values from my constructors to my method in my main program. I got a bit of help from my professor and he said to pass the X and Y values into my print board method I tried to use ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos in my print board declaration but I got an error about VariableDeclaratiorId. Here is my main as it is currently as is right now Java package ship; import java.util.*; public class ShipGame { public static String[][] makeBoard() { String[][] f = new String[6][22]; for (int i = 0; i < f.length; i++) { for (int j = 0; j < f[i].length; j++) { if (j % 2 == 0) f[i][j] = "|"; else f[i][j] = " "; } } return f; } public static void printBoard(String[][] f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos) { for (int i = 0; i < f.length; i++) { for (int j = 0; j < f[i].length; j++) { if(x == ship1.XPos && y == ship1.YPos){ System.out.print(ship1); } else if (x == ship2.XPos && y == ship2.YPos){ System.out.ptint(ship2); } else{ System.out.print(f[i][j]); } System.out.println(); } } } public static void main(String[] args) { int engine; System.out.println("Welcome First Captian! What kind of ship would you like to create: "); System.out.println("1. Battlecruiser"); System.out.println("2. Destroyer"); Scanner scan = new Scanner(System.in); engine = scan.nextInt(); scan.nextLine(); String engineType; if (engine == 1) { engineType = "Battlecrusier"; } else { engineType = "Destroyer"; } System.out.println("What would you like to name your vessel?"); String shipName1 = scan.nextLine(); Spaceship1 ship1 = new Spaceship1(shipName1, engineType); System.out.println("Welcome Second Captian! What kind of ship would you like to create: "); System.out.println("1. Battlecruiser"); System.out.println("2. Destroyer"); engine = scan.nextInt(); scan.nextLine(); if (engine == 1) { engineType = "Battlecrusier"; } else { engineType = "Destroyer"; } System.out.println("What would you like to name your vessel?"); String shipName2 = scan.nextLine(); Spaceship2 ship2 = new Spaceship2(shipName2, engineType); String[][] f = makeBoard(); int count = 0; printBoard(f); boolean gaming = true; while (gaming) { if (count % 2 == 0) { ship1.movement1(f); } else { ship2.movement2(f); } count++; printBoard(f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos ); gaming = false; } } } Here is my Spaceship1 constructor. It is the same as my Spaceship2 constructor so there's no need to add it Java package ship; import java.util.Random; import java.util.Scanner; public class Spaceship1 extends ship { private String ship1; public Spaceship1(String shipName, String engineType) { super(shipName, engineType); double maxSpeed = Math.random() * 2 + 1; int shipHealth = (int) (Math.random() * 100 + 50); int attackPower = (int) (Math.random() * 20 + 5); Random rand = new Random(); int newXPos = rand.nextInt(9); int newYPos = rand.nextInt(9); setShipHealth(shipHealth); setMaxSpeed(maxSpeed); setAttackPower(attackPower); setXPos(newXPos); setYPos(newYPos); } public void movement1(String[][] f) { System.out.println("W Move Up"); System.out.println("S Move Down"); System.out.println("A Move Left"); System.out.println("D Move Right"); Scanner scan = new Scanner(System.in); String move = scan.nextLine(); int standX = getXPos(); int standY = getYPos(); double standS = getMaxSpeed(); if(move == "W") { standY += standS; setYPos(standY); } else if(move == "S") { standY += standS; setYPos(standY); } else if(move == "A") { standY += standS; setYPos(standY); } else if(move == "D") { standY += standS; setYPos(standY); } } } I expect there to be the words Ship1 and Ship2 on any space on my game board that is declared as 6x22.
When you define a method, you need to define the arguments it accepts using their types and names that the method will use to refer to those arguments. For example, your code: public static void printBoard(String[][] f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos) should actually be written like so: public static void printBoard(String[][] f, int ship1Xpos, int ship1Ypos, int ship2Xpos, int ship2Ypos) The reason your code doesn't work is because you're trying to define the method using the values you want to pass into it (e.g., ship1.XPos). When you want to call the method, then you can give it the values that you want it to use, like so: printBoard(f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos); Keep in mind that you also have the following line of code which won't work because you're not passing a value for all of the arguments it expects: printBoard(f);
Java: Fixing array "linking" to allow for resetting
Firstly, I know Lists are better in almost(if not all) every way. I have encountered a substantial bug in an encoder program that I am making. In this program, I have a button that resets the "wheels" responsible for encoding(One of the wheels rotates after every letter encoded). I have a final int[][] called wheelsOriginal that is supposed to store the original value of the int[][] called wheels. Both of these arrays are int[9][36]. I would like a way of making wheelsOriginal stay unchanged throughout the program instead of changing with wheels for some reason. Here is a good way to recreate the problem(Sorry for the lengthy intToChar and charToInt methods!): Main class: import java.awt.*; import javax.swing.*; public class mainClass { public static void main(String[] args) { JFrame frame = new JFrame("Encoder"); frame.setBackground(new Color(225,225,225)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Display d = new Display(); frame.add(d); frame.pack(); frame.setResizable(false); frame.setVisible(true); } } Display class: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Display extends JPanel implements ActionListener { static JButton button; static JLabel letter; static int currentKey = -10; static int wheel = 0; static int[][] wheels = { {-3,10,-6,2,20,-7,22,5,23,4,6,-9,3,26,0,15,21,-2,13,14,12,1,17,11,-8,-5,18,8,24,9,25,7,19,16,-4,-1}, {9,22,14,12,18,-3,3,6,16,1,-7,25,24,19,-8,8,21,20,5,-6,-2,26,15,-9,23,10,11,0,-5,4,-4,2,17,-1,13,7}, {18,20,-9,15,12,-6,16,-4,-5,14,24,-7,-8,-3,-1,1,4,7,8,25,10,11,5,6,13,22,19,21,23,-2,3,26,17,9,0,2}, {-3,10,-6,2,20,-7,22,5,23,4,6,-9,3,26,0,15,21,-2,13,14,12,1,17,11,-8,-5,18,8,24,9,25,7,19,16,-4,-1}, {9,22,14,12,18,-3,3,6,16,1,-7,25,24,19,-8,8,21,20,5,-6,-2,26,15,-9,23,10,11,0,-5,4,-4,2,17,-1,13,7}, {25,18,5,8,7,-8,4,11,6,-7,26,21,-1,24,15,23,9,-6,-2,13,16,22,-5,10,17,3,1,-9,0,12,2,19,-4,14,20,-3}, {25,18,5,8,7,-8,4,11,6,-7,26,21,-1,24,15,23,9,-6,-2,13,16,22,-5,10,17,3,1,-9,0,12,2,19,-4,14,20,-3}, {25,18,5,8,7,-8,4,11,6,-7,26,21,-1,24,15,23,9,-6,-2,13,16,22,-5,10,17,3,1,-9,0,12,2,19,-4,14,20,-3}, {9,22,14,12,18,-3,3,6,16,1,-7,25,24,19,-8,8,21,20,5,-6,-2,26,15,-9,23,10,11,0,-5,4,-4,2,17,-1,13,7} }; final static int[][] wheelsOriginal = wheels; public Display() { setPreferredSize(new Dimension(250,200)); setFocusable(true); button = new JButton("Reset"); button.setPreferredSize(new Dimension(225,50)); button.setFont(new Font(button.getFont().getFontName(), button.getFont().getStyle(), 25)); letter = new JLabel(" ", SwingConstants.CENTER); letter.setPreferredSize(new Dimension(225,100)); letter.setFont(new Font(letter.getFont().getFontName(), Font.BOLD, 125)); letter.setForeground(new Color(0,0,0)); addKeyListener( new KeyListener() { public void keyPressed(KeyEvent e) { if(currentKey == -10 && e.getKeyCode() >= 65 && e.getKeyCode() <= 90) { currentKey = e.getKeyCode() - 64; letter.setText(encode() + ""); } else if(currentKey == -10 && e.getKeyCode() >= 48 && e.getKeyCode() <= 57) { currentKey = -1 * (e.getKeyCode() - 48); letter.setText(encode() + ""); } } public void keyReleased(KeyEvent e) { currentKey = -10; letter.setText(" "); } public void keyTyped(KeyEvent e) {} } ); button.addActionListener(this); add(button, TOP_ALIGNMENT); add(letter); } public static char encode() { int key = currentKey; for(int i = 0; i < 9; i++) { key = wheels[i][key + 9]; } for(int i = 8; i >= 0; i--) { key = wheels[i][key + 9]; } rotate(wheels[wheel], isEven(wheel)); if(wheel < 8) { wheel++; } else { wheel = 0; } return((char) key); } public static int[] rotate(int[] wheel, boolean positive) { int revolve; if(positive) { revolve = wheel[wheel.length - 1]; for(int i = wheel.length - 2; i > 0; i--) { wheel[i + 1] = wheel[i]; } wheel[0] = revolve; } else { revolve = wheel[0]; for(int i = 1; i < wheel.length - 1; i++) { wheel[i - 1] = wheel[i]; } wheel[wheel.length - 1] = revolve; } return wheel; } public static boolean isEven(int num) { return (num/2 == Math.abs(num/2)); } public void actionPerformed(ActionEvent e) { if(e.getSource().equals(button)) { reset(); grabFocus(); } } public static void reset() { for(int[] i : wheels) { for(int x : i) { System.out.print(x + " "); } System.out.println(""); } System.out.println(" "); for(int[] i : wheelsOriginal) { for(int x : i) { System.out.print(x + " "); } System.out.println(""); } System.out.println(" "); wheels = wheelsOriginal; for(int[] i : wheels) { for(int x : i) { System.out.print(x + " "); } System.out.println(""); } wheel = 0; letter.setText(" "); currentKey = ' '; System.out.println("Pressed"); } } Whenever a key is pressed, the encoded letter appears in the window. Even pressing the same key over and over again will usually produce different letters. Pressing the reset button should reset the encoder so that pressing the letter 'A' three times should produce S, E, and Q in that order. I also have designed this so that whenever you press the reset button, three large bulks of numbers print in the console. These show the wheels array before reset, the wheelsOriginal array, and the product wheels array in that order. If you press keys and click reset several times, you will notice that wheelsOriginal changes with wheels. Please help...
Your problem is that you are creating wheelsOriginal as reference of wheels instead of copy. Thats why when you change wheels, wheelsOriginal changes as well. final static int[][] wheelsOriginal = wheels; Something like this loop can be used to create a copy of wheels int[][] wheelsOriginal = new int[wheels.length][]; for( int i = 0; i < wheelsOriginal.length; i++ ) { wheelsOriginal[i] = Arrays.copyOf( wheels[i], wheels[i].length ); } Also, for your charToInt and IntToChar methods - you could use the fact that chars are numbers and a->z A->Z 0->9 are grouped together to shorten them significantly I didn't test that - in case you decide to use something like this - think and test yourself public int charToInt( char c ) { if( c >= '0' && c <= '9' ) { return '0' - c; } else if( c >= 'A' && c <= 'Z' ) { return c - 'A' + 1; } else if( c >= 'a' && c <= 'z' ) { return c - 'a' + 1; } else { return -10; } } public char intToChar( int c ) { if( c >= -9 && c <= 0 ){ return (char)('0' - c); } else if( c >= 1 && c <= 26 ){ return (char)(c + 'A' - 1); } else{ return ' '; } }
For Loop to score bowling
I'm working on a project for a potential internship to take a String input of bowling scores and add them up to a final score. I'm having difficult passing one of my tests and was wondering if you could help me figure out my fault. The test that is not working is isNinetySix and it is giving me a result of 98 instead. Please help! public class Game { private int roll = 0; private int[] rolls = new int[21]; public void rolls(String scoreCard) { for (int i=0; i< scoreCard.length(); i++) { if (scoreCard.charAt(i) == 'X') { rolls[roll++] = 10; } else if (scoreCard.charAt(i) == '/') { rolls[roll++] = 10; } else if (scoreCard.charAt(i) == '-') { } else { int x = scoreCard.charAt(i); rolls[roll++] = x - '0'; } } } public int score() { int score = 0; int cursor = 0; for (int frame = 0; frame < 10; frame++) { if (isStrike(cursor)) { score += 10 + rolls[cursor+1] + rolls[cursor+2]; cursor ++; } else if (isSpare(cursor)) { score += 10 + rolls[cursor+2]; cursor += 2; } else { score += rolls[cursor] + rolls[cursor+1]; cursor += 2; } } return score; } private boolean isStrike(int cursor) { return rolls[cursor] == 10; } private boolean isSpare(int cursor) { return rolls[cursor] + rolls[cursor+1] == 10; } //Print scores for each frame public void printFrameScore(int[] frame) { for (int i = 1; i < frame.length; i++) { System.out.println(i + ": " + frame[i]); } } public void displayRolls() { for (int i = 0; i < rolls.length; i++) { System.out.print(rolls[i] + ", "); } } } Tests import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.is; import org.junit.Before; import org.junit.Test; public class GameTest { private Game game; #Before public void setUp(){ game = new Game(); } #Test public void isPerfect() { game.rolls("X-X-X-X-X-X-X-X-X-X-XX"); assertThat(game.score(), is(300)); } #Test public void isGutter() { game.rolls("00-00-00-00-00-00-00-00-00-00"); assertThat(game.score(), is(0)); } #Test public void isNinety() { game.rolls("45-54-36-27-09-63-81-18-90-72"); assertThat(game.score(), is(90)); } #Test public void isOneFifty(){ game.rolls("5/-5/-5/-5/-5/-5/-5/-5/-5/-5/-5"); assertThat(game.score(), is(150)); } #Test public void isNinetySix() { game.rolls("45-54-36-27-09-63-81-18-90-7/-5"); assertThat(game.score(), is(96)); } }
The problem here seems to be that your isSpare() function never returns true because you assigned each / a value of 10. The result of the addition of the two rolls in a frame with a spare was more than 10. If I were you I would try to clean up the assignment of / to actually be 10 - prev_role_score. This would be cleaner than making isSpare() check for greater than 10. There are other ways to clean up the code to, you could try to refactor some to impress whoever you submit to. } else if (scoreCard.charAt(i) == '/') { int diff = 10 - rolls[roll - 1]; rolls[roll++] = diff; }
Your code is failing in the below block (after your 9th frame, you're at a score of 81). You're code is looking at the index that contains the value 7 and the / which you represent as 10, thereby giving you 17 rather than 10 for the spare. ... } else { score += rolls[cursor] + rolls[cursor+1]; cursor += 2; } ... So, if I were making suggestions, and I'm not sure what the expectations are for your project, I would tell you to think about easier ways to traverse your string by splitting, searching, then adding. Below is a quick example: public void rolls(String scorecard) { String [] framesets = scorecard.split("-"); //hunt for special cases like spare and strikes //do work to hold your scores }
Memory game does not call compare function correctly
I have coded a simple memory game. Card values are added to two arrays and after that, a compare function is called. But there is a problem with the logic of the compare function. The specific problem seems related to the fact that the compare function is called on the third button click. So on first click it adds first value to first array , on second click second value to second array. But I must click for yet a third time to call the compare function to compare the match of two arrays. The main problem is that after all cards are inverted (10 matches in 5x4 memory game), it does not show the result. I have uploaded full code here : http://uloz.to/xcsJkYUK/memory-game-rar . public class PEXESO5x4 extends JFrame implements ActionListener { private JButton[] aHracieTlactika = new JButton[20]; private ArrayList<Integer> aHodnoty = new ArrayList<Integer>(); private int aPocitadlo = 1; private int[] aTlacitkoIden = new int[2]; private int[] aHodnotaTlac = new int[2]; private JButton aTlacitkoExit; private JButton aTlacitkoReplay; private JButton[] aHracieTlacitko = new JButton[20]; private int aPocetTahov = 0; public void vkladanieHodnot() { for (int i = 0; i < 2; i++) { for (int j = 1; j < (this.aHracieTlactika.length / 2) + 1; j++) { this.aHodnoty.add(j); } } Collections.shuffle(this.aHodnoty); } public boolean zhoda() { if (this.aHodnotaTlac[0] == this.aHodnotaTlac[1]) { return true; } return false; } public void zapisCislaDoSuboru() { try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Semestralka.txt", true)))) { out.println("haha"); //more code out.println("hahahahha"); //more code }catch (IOException e) { //exception handling left as an exercise for the reader } } public void actionPerformed(ActionEvent e) { int match = 0; if (this.aTlacitkoExit == e.getSource()) { System.exit(0); } if (this.aTlacitkoReplay == e.getSource()) { } for (int i = 0; i < this.aHracieTlactika.length; i++) { if (this.aHracieTlactika[i] == e.getSource()) { this.aHracieTlactika[i].setText("" + this.aHodnoty.get(i)); this.aHracieTlactika[i].setEnabled(false); this.aPocitadlo++; this.aPocetTahov += 1; if (this.aPocitadlo == 3) { if (this.zhoda()) { match+=1; if (match==10) { System.out.println("You win"); } this.aHracieTlactika[this.aTlacitkoIden[0]].setEnabled(false); this.aHracieTlactika[this.aTlacitkoIden[1]].setEnabled(false); } else { this.aHracieTlactika[this.aTlacitkoIden[0]].setEnabled(true); this.aHracieTlactika[this.aTlacitkoIden[0]].setText(""); this.aHracieTlactika[this.aTlacitkoIden[1]].setEnabled(true); this.aHracieTlactika[this.aTlacitkoIden[1]].setText(""); } this.aPocitadlo = 1; } if (this.aPocitadlo == 1) { this.aTlacitkoIden[0] = i; this.aHodnotaTlac[0] = this.aHodnoty.get(i); } if (this.aPocitadlo == 2) { this.aTlacitkoIden[1] = i; this.aHodnotaTlac[1] = this.aHodnoty.get(i); } } } } }
Java IO, reading from a file and printing to a 2d character array
So I'm working on an assignment for my game design class to build a pacman clone, it'll be throughout the semester. Currently I've got a text file that is the pacman maze see below : WWWWWWWWWWWWWWWWWWWWWWWWWWWW W............WW............W W.WWWW.WWWWW.WW.WWWWW.WWWW.W W*WWWW.WWWWW.WW.WWWWW.WWWW*W W.WWWW.WWWWW.WW.WWWWW.WWWW.W W..........................W W.WWWW.WW.WWWWWWWW.WW.WWWW.W W.WWWW.WW.WWWWWWWW.WW.WWWW.W W......WW....WW....WW......W WWWWWW.WWWWW.WW.WWWWW.WWWWWW WWWWWW.WWWWW.WW.WWWWW.WWWWWW WWWWWW.WW..........WW.WWWWWW WWWWWW.WW.WWWWWWWW.WW.WWWWWW WWWWWW.WW.WWWWWWWW.WW.WWWWWW ..........WWWWWWWW.......... WWWWWW.WW.WWWWWWWW.WW.WWWWWW WWWWWW.WW.WWWWWWWW.WW.WWWWWW WWWWWW.WW..........WW.WWWWWW WWWWWW.WW.WWWWWWWW.WW.WWWWWW WWWWWW.WW.WWWWWWWW.WW.WWWWWW W............WW............W W.WWWW.WWWWW.WW.WWWWW.WWWW.W W*WWWW.WWWWW.WW.WWWWW.WWWW*W W...WW................WW...W WWW.WW.WW.WWWWWWWW.WW.WW.WWW WWW.WW.WW.WWWWWWWW.WW.WW.WWW W......WW....WW....WW......W W.WWWWWWWWWW.WW.WWWWWWWWWW.W W.WWWWWWWWWW.WW.WWWWWWWWWW.W W..........................W WWWWWWWWWWWWWWWWWWWWWWWWWWWW the idea is that this is read in, line by line by a reader from the java io package and then used to populate a 2d array, I think then I can use a loop to specify where to print images using the paint class with the data in the array. My problem currently is the paint method, it doesnt seem to be working at all but I cant find what's wrong with it at the moment. Can anyone point me in the right direction? (My codes formatting has been messed up a tad by indentation required here, I'm also new to the java IO package, first time I've seen exception handling!) Thanks in advance for any help! //imports import java.awt.*; import java.io.*; import javax.swing.*; public class Maze extends JFrame { //V.Decleration private static final Dimension WindowSize = new Dimension (600,600); static char[][] Amaze = new char[28][31]; //default constructor public Maze() { this.setTitle("Pacman"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); int x = screensize.width/2 - WindowSize.width/2; int y = screensize.height/2 - WindowSize.height/2; setBounds(x, y, WindowSize.width, WindowSize.height); setVisible(true); } public void paint (Graphics g) { String line = null; try { BufferedReader reader = new BufferedReader(new FileReader("G:\\Game Design\\Pacman\\src\\Maze.txt")); for (int i=0; i<=31; i++) { do { try { line=reader.readLine(); for (int y=0; y<=28; y++) { Amaze[y][i]=line.charAt(y); } }catch (IOException e) { } } while (line!= null); try { reader.close(); } catch (IOException e) { } } } catch (FileNotFoundException e) {} } //main public static void main (String [] args) { Maze maze = new Maze(); for (int i=0;i<=28;i++) System.out.print(Amaze[i][31]); } }
You are creating an array that is too small for the loop. Namely: new char[28][31]; will only allow for a maximum index of 27 and 30. Your for loops are: for (int i=0; i<=31; i++) for (int y=0; y<=28; y++) Use i<31 and y<28, or increase your array to be [29][32]. Either one of these should solve your current problem.
Three suggestions: It may be less misleading to separate your functions to do just one job at a time. So there should be a function to read the file and then another to paint the results. Put more System.out.println() statements in your code when you're trying to debug. That's a good way to check whether each part did what you intended. For example, printing the line variable after reading it in would at least let you know whether you were reading the file correctly. Always print out your exceptions. They will tell you what went wrong and where. That said, this code will load and print your maze: import java.io.*; public class Read2DArray { private final int WIDTH = 28; private final int HEIGHT = 31; private char[][] maze = new char[WIDTH][HEIGHT]; public static void main(String[] args) { Read2DArray array = new Read2DArray(); array.loadFile("maze.txt"); array.printArray(); } public void loadFile(String fname) { try { BufferedReader reader = new BufferedReader(new FileReader(fname)); String line; int col = 0, row = 0; while((line = reader.readLine()) != null && row < HEIGHT) { for(col = 0; col < line.length() && col < WIDTH; col++) { maze[col][row] = line.charAt(col); } row++; } reader.close(); } catch(IOException e) { e.printStackTrace(); } } public void printArray() { for(int row = 0; row < HEIGHT; row++) { for(int col = 0; col < WIDTH; col++) { System.out.print(maze[col][row]); } System.out.println(); } } }