JInput's getPollData() does not work - java

I´m currently dealing with some Problems concerning dual mouse input. I've looked up several libraries and decided that JInput would do best. Although i was able to get a list of all devices plugged into my laptop, i couldn't retrieve any PollData. The following code only produces 0's:
public static void main(String[] args) {
Controller mouse1 = null;
Controller[] cs = ControllerEnvironment.getDefaultEnvironment().getControllers();
for(int i = 0; i < cs.length; i++) {
if(cs[i].getType() == Type.MOUSE) {
mouse1 = cs[i];
}
}
mouse1.poll();
Component[] comps = mouse1.getComponents();
while(true) {
mouse1.poll();
for(int i = 0; i < comps.length; i++) {
System.out.print(comps[i].getName() + ": ");
System.out.println(comps[i].getPollData());
}
}
}
I also tried out to get KeyBoard-Input with this, same problem. I could get the number of keys, but i was unable to access any information about the key's state.
I hope that someone knows how to solve this problem or has an idea what might be causing it.
Thank you in advance, aquatyp.

I know this is almost a year old, but for the benefit of anyone who finds this through Google like I did...
Make sure you have an OpenGL display initialized (note the if statement is there just to eliminate the flood of messages):
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
import net.java.games.input.Mouse;
import net.java.games.input.RawInputEnvironmentPlugin;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
public class Main
{
public static void main(String[] args)
{
try
{
Display.setDisplayMode(new DisplayMode(800,600));
Display.create();
}
catch (LWJGLException e)
{
e.printStackTrace();
System.exit(0);
}
RawInputEnvironmentPlugin rep = new RawInputEnvironmentPlugin();
Mouse mouse;
StringBuilder sb = new StringBuilder();
while (!Display.isCloseRequested())
{
int i = 0;
for (Controller controller : ControllerEnvironment.getDefaultEnvironment().getControllers())
{
if (controller.getType() == Controller.Type.MOUSE)
{
//System.out.println(controller.getName() + " | " + controller.getType());
mouse = (Mouse)controller;
mouse.poll();
i += 1;
if (mouse.getX().getPollData() > 0.0f || mouse.getY().getPollData() > 0.0f)
{
sb.append("[");
sb.append(i);
sb.append("] X=");
sb.append(mouse.getX().getPollData());
sb.append(" Y=");
sb.append(mouse.getY().getPollData());
System.out.println(sb.toString());
sb.setLength(0);
}
}
}
Display.update();
}
}
}

Related

Error char arrays from RandomAccessFile in Java

I'm using RandomAccessFile to browse thru a series of records in a .dat file. I'm using the GUI interface. I have no problem writing the Strings from the textFields into the file, but when I try to read it back into the fields, the first record called looks fine, but by the third record the fields just display some strange encoded characters. Does this have something to do with an offset? Does it have something to do with the way I increment through the records? I've looked all over the web today and I'm stuck. Here's a sample of my code.
Read/write methods:
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class StudentFile6 {
private final int R_SIZE = 70;
private final RandomAccessFile studentFile;
public StudentFile6(String fileName) throws IOException {
studentFile = new RandomAccessFile(fileName, "rw");
}
public void writeStudentFile(Student6 student) throws IOException {
studentFile.seek(studentFile.length());
if (student.getFirst().length() > 15) {
for (int i = 0; i < 15; i++) {
studentFile.writeChar(student.getFirst().charAt(i));
}
} else {
studentFile.writeChars(student.getFirst());
for (int i = 0; i < (15 - student.getFirst().length()); i++) {
studentFile.writeChar(' ');
}
}
if (student.getLast().length() > 15) {
for (int i = 0; i < 15; i++) {
studentFile.writeChar(student.getLast().charAt(i));
}
} else {
studentFile.writeChars(student.getLast());
for (int i = 0; i < (15 - student.getLast().length()); i++) {
studentFile.writeChar(' ');
}
}
if (student.getID().length() > 5) {
for (int i = 0; i < 5; i++) {
studentFile.writeChar(student.getID().charAt(i));
}
} else {
studentFile.writeChars(student.getID());
for (int i = 0; i < (5 - student.getID().length()); i++) {
studentFile.writeChar(' ');
}
}
}
public Student6 readStudentFile(int count) throws IOException,
EOFException{
char[] firstCharArray = new char[15];
char[] lastCharArray = new char[15];
char[] idCharArray = new char[5];
studentFile.seek(count * 35);
for (int i = 0; i < 15; i++) {
firstCharArray[i] = studentFile.readChar();
}
String first = new String(firstCharArray);
studentFile.seek(count * 35 + 30);
for (int i = 0; i < 15; i++) {
lastCharArray[i] = studentFile.readChar();
}
String last = new String(lastCharArray);
studentFile.seek(count * 35 + 60);
for (int i = 0; i < 5; i++) {
idCharArray[i] = studentFile.readChar();
}
String ID = new String(idCharArray);
Student6 student = new Student6(first, last, ID);
return student;
}
Here's what I think is the relevant code from the class that calls these methods:
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class FinalExam6 extends JFrame {
private int recordNum = 0;
//there are more static variables, but this is the only one i use to write
//and read
//lots of code setting up my GUI interface....
//Here's the code that handles writing my RandomAccessFile:
private class AddStudentButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
try {
String first = txtFirst.getText();
String last = txtLast.getText();
String ID = txtID.getText();
Student6 student = new Student6(first, last, ID);
StudentFile6 studentFile = new StudentFile6("StudentInfo.dat");
student.setFirst(first);
student.setLast(last);
student.setID(ID);
studentFile.writeStudentFile(student);
txtFirst.setText("");
txtLast.setText("");
txtID.setText("");
} catch (IOException ex) {
}
}
//Here's the code that reads it:
private class BrowseStudentListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
try {
recordNum++;
StudentFile6 studentFile = new StudentFile6("StudentInfo.dat");
txtFirst.setText
(studentFile.readStudentFile(recordNum).getFirst());
txtLast.setText(studentFile.readStudentFile(recordNum).getLast());
txtID.setText(studentFile.readStudentFile(recordNum).getID());
studentFile.close();
} catch (IOException ex) {
}
}
}
I realize i might be missing some brackets in here or there doing copy/past. Any help is greatly appreciated.
Your record size is 70 bytes (private final int R_SIZE = 70;). That matches with writing 35 chars (at 2 bytes for each char).
However for calculating the position of a record you write
studentFile.seek(count * 35);
which will place your read pointer in the middle of some record for odd count values.
At least the (unnecessary) line
studentFile.seek(count * 35 + 60);
should have told you that something is wrong!

How to plot a waveform using PortAudio in Java (jpab with Processing)?

I need to access multiple audio inputs in Java so first consulted SO and found this answer and deviced to use PortAudio Java bindings (jpab). Unfortunately I found little and outdated documentation.
With what I've found I tried this using Processing in eclipse:
import java.nio.ByteBuffer;
import org.jpab.Callback;
import org.jpab.Device;
import org.jpab.PortAudio;
import org.jpab.PortAudioException;
import org.jpab.Stream;
import org.jpab.StreamConfiguration;
import org.jpab.StreamConfiguration.Mode;
import org.jpab.StreamConfiguration.SampleFormat;
import processing.core.PApplet;
public class PortAudioPlot extends PApplet implements Callback {
float min = 1000000,max = 0;
public void setup(){
try {
PortAudio.initialize();
for(Device d : PortAudio.getDevices()) println(d);
Device d = PortAudio.getDevices().get(1);// Microphone (Realtek High Definition Audio)
if(d.getMaxInputChannels() > 0){
println(d.getName());
StreamConfiguration sc = new StreamConfiguration();
sc.setInputDevice(d);
sc.setInputFormat(SampleFormat.SIGNED_INTEGER_16);
sc.setMode(Mode.INPUT_ONLY);
sc.setSampleRate(44100);
sc.setInputChannels(d.getMaxInputChannels());
PortAudio.createStream(sc, this, new Runnable() {
public void run() {
try {
PortAudio.terminate();
} catch (PortAudioException ignore) { ignore.printStackTrace(); }
}
}).start();
}
} catch (PortAudioException e) {
e.printStackTrace();
}
}
public void draw(){
if(keyPressed && key == 's') saveFrame(dataPath("frame-####.jpg"));
}
public void stop(){
try {
PortAudio.terminate();
} catch (PortAudioException e) {
e.printStackTrace();
}
super.stop();
}
public static void main(String[] args) {
PApplet.main(PortAudioPlot.class.getSimpleName());
}
#Override
public State callback(ByteBuffer in, ByteBuffer out) {
int size = in.capacity();
println("in size: " + size + " min: " + min + " max: " + max);
background(255);
beginShape(LINES);
for (int i = 0; i < size; i++) {
float v = in.getFloat(i);
if(!Float.isNaN(v) && v != Float.POSITIVE_INFINITY && v != Float.NEGATIVE_INFINITY){
float x = (float)i/size * width;
float y = (height * .5f) + (v * .5f);
if(v < min) min = v;
if(v > max) max = v;
vertex(x,y);
}
}
endShape();
return State.ABORTED;
}
}
I started with the mic 1st and I think I'm getting close as I can seem some values, but I'm not 100% sure I'm traversing the input ByteBuffer correctly.
What is the correct way to access values and plot a waveform from an audio input using jpab ?
I've updated the code a wee bit and managed to get something closer to a plot, but I'm still in the dark. What are the correct min/max ranges for floats read from the input ByteBuffer ? Am I using it the right way ?
Here's a quick preview of what I've got:
I've also uploaded the eclipse project here. It's using the prebuilt Windows x86 PortAudio binaries.
Another update:
i was advised that the values should be from -1.0 to 1.0 and adjusted my code to map/clamp for this, but I'm not sure if this true.
Here is an updated example:
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.jpab.Callback;
import org.jpab.Device;
import org.jpab.PortAudio;
import org.jpab.PortAudioException;
import org.jpab.Stream;
import org.jpab.StreamConfiguration;
import org.jpab.StreamConfiguration.Mode;
import org.jpab.StreamConfiguration.SampleFormat;
import processing.core.PApplet;
public class PortAudioPlot extends PApplet implements Callback {
int[] pix;
int hh;//half height
int py;//y for each channel plot
int numChannels;
int pad = 5;
public void setup(){
try {
colorMode(HSB,360,100,100);
hh = height/2;
pix = new int[width*height];
PortAudio.initialize();
for(Device d : PortAudio.getDevices()) println(d);
Device d = PortAudio.getDevices().get(1);// Microphone (Realtek High Definition Audio)
numChannels = d.getMaxInputChannels();
py = height / numChannels;
if(numChannels > 0){
println(d.getName()+" sr:" + d.getDefaultSampleRate());
StreamConfiguration sc = new StreamConfiguration();
sc.setInputLatency(d.getDefaultLowInputLatency());
sc.setInputDevice(d);
sc.setInputFormat(SampleFormat.SIGNED_INTEGER_16);
sc.setMode(Mode.INPUT_ONLY);
sc.setSampleRate(d.getDefaultSampleRate());
sc.setInputChannels(numChannels);
PortAudio.createStream(sc, this, new Runnable() {
public void run() {
try {
PortAudio.terminate();
} catch (PortAudioException ignore) { ignore.printStackTrace(); }
}
}).start();
}
} catch (PortAudioException e) {
e.printStackTrace();
}
}
public void draw(){
loadPixels();
arrayCopy(pix, pixels);
updatePixels();
if(keyPressed && key == 's') saveFrame(dataPath("frame-####.jpg"));
}
public void stop(){
try {
PortAudio.terminate();
} catch (PortAudioException e) {
e.printStackTrace();
}
super.stop();
}
public static void main(String[] args) {
PApplet.main(PortAudioPlot.class.getSimpleName());
}
#Override
public State callback(ByteBuffer in, ByteBuffer out) {
int size = in.capacity();
println("in size: " + size);
Arrays.fill(pix, color(0,0,100));
for (int i = 0; i < width; i++) {
int ch = i%numChannels;//channel id
int sy = py * ch;//channel plot y starting position
int minY = sy+pad;//min y for min input value
int maxY = (sy*2)-pad;//min y for min input value
int buffIndex = i * size / width;//map i(x pixel index) to buffer index
float v = in.getFloat(buffIndex);
if(!Float.isNaN(v) && v != Float.POSITIVE_INFINITY && v != Float.NEGATIVE_INFINITY){
int vOffset = constrain((int)map(v,-1.0f,1.0f,minY,maxY),minY,maxY);
pix[vOffset * height + i] = color(map(ch,0,numChannels,0,360),100,50);
}
}
return State.RUNNING;
}
}
I've also noticed that the input ByteBuffer count changes when I setup latency.
And another confusing thing I noticed: JPAB is not the same as jportaudio, although most the API is similar, excepting createStream(jpab)/openStream(jportaudio). I haven't found a compiled version of jportaudio and haven't managed to compile it myself on Windows so far.
Any clues on how I can continue ?
The end goal is to access multiple audio inputs and this route at this point in time doesn't seem to lead anywhere.
The simplest solution which I've tested on Windows and OSX, is easy to setup and works in plain Java but quite nicely in Processing as well is using Beads which can connect to JACK. See this thread for more details, especially the later part about JNAJack (JJack is no longer maintained). I've used this version of Beads(download link) and JNA(download link).
Here's a basic code sample I used to test:
import java.util.Arrays;
import org.jaudiolibs.beads.AudioServerIO;
import net.beadsproject.beads.core.AudioContext;
import net.beadsproject.beads.core.AudioIO;
import net.beadsproject.beads.core.UGen;
import net.beadsproject.beads.ugens.Gain;
import processing.core.PApplet;
public class BeadsJNA extends PApplet {
AudioContext ac;
public void setup(){
ac = new AudioContext(new AudioServerIO.Jack(),512,AudioContext.defaultAudioFormat(4,2));//control number of ins(4) and outs(2)
UGen microphoneIn = ac.getAudioInput();
Gain g = new Gain(ac, 1, 0.5f);
g.addInput(microphoneIn);
ac.out.addInput(g);
println("no. of inputs: " + ac.getAudioInput().getOuts());
ac.start();
}
public void draw(){
loadPixels();
Arrays.fill(pixels, color(0));
for(int i = 0; i < width; i++)
{
int buffIndex = i * ac.getBufferSize() / width;
int vOffset = (int)((1 + ac.out.getValue(0, buffIndex)) * height / 2);
pixels[vOffset * height + i] = color(255);
}
updatePixels();
}
public static void main(String[] args) {
PApplet.main(BeadsJNA.class.getSimpleName());
}
}
This worked for me at this stage in time so is a valid answer
until someone will share an easy way to use jpab/jportaudio on Windows
to plot the waveform from an input.

Conway's game of life problems

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.

Finding an Image Within an Image in Java

I have been trying for hours to make this work, but for some reason, it is not finding matches. You can test it out with any image, but it should be taking a screenshot of the top left corner of the screen (1000px by 1000px) and finding the specified image within it. Any help would be greatly appreciated!
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageRobotTester {
/**
* #param args
*/
public static void main(String[] args) {
ImageRobot i = new ImageRobot();
try {
BufferedImage settingsImage = ImageIO.read(new File("images/Dex.png"));
Robot r = new Robot();
BufferedImage screen = r.createScreenCapture(new Rectangle(0, 0, 1000, 1000));
i.subImage(settingsImage, screen);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class ImageRobot {
public ImageRobot() {
// TODO Auto-generated constructor stub
}
public void subImage(BufferedImage needle, BufferedImage hayStack)
{
int xMatch = 0;
int yMatch = 0;
int possMatches = 0;
try {
for(int j = 0; j < hayStack.getHeight() - needle.getHeight(); j++)
{
for(int i = 0; i < hayStack.getWidth() - needle.getWidth(); i++)
{
BufferedImage hayStackSub = hayStack.getSubimage(i, j, needle.getWidth(), needle.getHeight());
if(hayStackSub.equals(needle))
{
System.out.println("match!");
xMatch = i;
yMatch = j;
}
}
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Out of bounds! (" + xMatch + ", " + yMatch + ")");
}
System.out.println("(" + xMatch + ", " + yMatch + ")");
}
}
Correct me if I am wrong, but are you trying to do some kind of image recognition here?
You are not searching for a sub-image that matches the reference image pixel by pixel, but you are searching for a similar image? Right?
In this case you need to move a small "window" over your big image (like you are doing right now with your double for loop), but instead of using "equals", use a properly trained neural network to tell if the image you are looking for is inside that window.
See this tutorial for details on how to build a NN based image recognizer:
http://neuroph.sourceforge.net/image_recognition.html

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();
}
}
}

Categories