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!
Related
I developed a game and I want to keep track of the Top-3 Best Scores in a file, so that we don't lose the Scores after closing the game. It's not working properly and I don't know why.
- The Best Scores are Integers, and the lowest it is the better. The Best Score is the lowest.
- It is not saving the Scores in ascending Order
It does create a file and it appears to work with the main tests but after a few Scores being add, it does not sort the array in ascending order, so the file is in the wrong way.
package pt.iscte.dcti.poo.sokoban.starter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
import pt.iul.ista.poo.utils.Point2D;
public class BestScores {
public int[] bestScore = new int[3];
public final int level;
public BestScores(int level) {
this.level = level;
}
public int[] getBestScore() {
return bestScore;
}
//Register BestScores
public void setBestScore(int score) {
for(int i = 0; i < bestScore.length; i++) {
if(bestScore[i] == 0) {
bestScore[i] = score;
return;
}
}
Arrays.sort(bestScore);
for (int i = 0; i < bestScore.length-1; i++) {
if(bestScore[i] == 0) {
int box1 = bestScore[i];
bestScore[i] = bestScore[i+1];
bestScore[i+1] = box1;
}
}
addBestScore(score);
}
public void addBestScore(int score) {
if(score < bestScore[bestScore.length - 1])
bestScore[bestScore.length - 1] = score;
Arrays.sort(bestScore);
for (int i = 0; i < bestScore.length-1; i++) {
if(bestScore[i] == 0) {
int box1 = bestScore[i];
bestScore[i] = bestScore[i+1];
bestScore[i+1] = box1;
}
}
}
public int getTopOne() {
return bestScore[0];
}
public int getLevel() {
return level;
}
//Check if the file exists, else create it
public void searchFile() {
File tmpDir = new File("bestScores/BestScore_" + level + ".txt");
if (!tmpDir.exists())
createOrAddScore();
else {
checkScores(tmpDir);
createOrAddScore();
}
}
//Create file with Scores if they exist.
public void createOrAddScore() {
try {
PrintWriter writer = new PrintWriter(new File("bestScores/BestScore_" + level + ".txt"));
writer.println("BestScores: ************Level:" + level + "************");
for(int i = 0; i < bestScore.length; i++) {
if(bestScore[i] != 0)
writer.println((i+1) + "ยบ " + bestScore[i] + " " + "moves.");
}
writer.close();
}
catch (FileNotFoundException e) {
System.err.println("problema a escrever o ficheiro");
}
}
//Read File and return Best Scores, so that we don't lose the bestScores even after closing the game :D.
public void checkScores(File file) {
int[] array = new int[3];
try {
Scanner scanner = new Scanner(file);
String title_line = scanner.nextLine();
int i = 0;
while(scanner.hasNextLine()) {
String[] line = scanner.nextLine().split(" ");
array[i] = Integer.parseInt(line[1]);
i++;
}
}
catch (FileNotFoundException e) {
System.err.println("problema a escrever o ficheiro");
}
for (int i = 0; i < array.length; i++)
if(array[i] != 0)
setBestScore(array[i]);
}
public static void main(String[] args) {
// BestScores bS = new BestScores(4);
//test1 No BEstScores
// bS.searchFile();
//test2 WithBestScores
// bS.setBestScore(40);
// bS.setBestScore(15);
bS.setBestScore(50);
// bS.setBestScore(30);
// bS.setBestScore(10);
// bS.searchFile();
// int[] test = bS.getBestScore();
// for(int i = 0; i < test.length; i++)
// System.out.println(test[i]);
//test3 With file with Scores
// bS.searchFile();
// int[] test = bS.getBestScore();
// for(int i = 0; i < test.length; i++)
// System.out.println(test[i]);
}
}
So here's my problem :
I have two arrays, I want to count how many values are on the exact same position [i] on both arrays, and how many values are the same on both arrays but for different [i]
I tried the usual loop with for and the size of an array but it displays strange values that are far from what expected
package stackOverflow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class mainStack extends JFrame implements ActionListener {
JButton jbr,jbv,jbb,jbo,jbn,jbj;
JTextField l11b;
String a;
int tabRef[]= {0,1,2,3};
int correctAndSameCase=0;
int correctButDiffCase=0;
mainStack(){
this.setLayout(null);
jbr = new JButton("Rouge");
jbr.setBounds(0,80,85,30);
add(jbr);
jbv = new JButton("Vert");
jbv.setBounds(125, 80, 85, 30);
add(jbv);
jbb = new JButton("Bleu");
jbb.setBounds(0, 120, 85, 30);
add(jbb);
jbj = new JButton("Jaune");
jbj.setBounds(125, 120, 85, 30);
add(jbj);
jbo = new JButton("Orange");
jbo.setBounds(0, 160, 85,30);
add(jbo);
jbn = new JButton("Noir");
jbn.setBounds(125,160, 85,30);
add(jbn);
jbr.addActionListener(this);
jbv.addActionListener(this);
jbb.addActionListener(this);
jbj.addActionListener(this);
jbo.addActionListener(this);
jbn.addActionListener(this);
setLayout(null);
setSize(800,800);
setVisible(true);
}
private int index = 0;
private int p=0;
private int tabAnswer[][] = new int[3][4];
private int i;
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(jbr)) {
tabAnswer[p][index] = 0;
} else if (e.getSource().equals(jbv)) {
tabAnswer[p][index] = 1;
} else if (e.getSource().equals(jbj)) {
tabAnswer[p][index] = 2;
} else if (e.getSource().equals(jbb)) {
tabAnswer[p][index] = 3;
} else if (e.getSource().equals(jbo)) {
tabAnswer[p][index] = 4;
} else if (e.getSource().equals(jbn)) {
tabAnswer[p][index] = 5;
}
index++;
if (index >= tabAnswer[p].length) {
System.out.println(Arrays.toString(tabAnswer[p]));
for(i=0 ; i<tabRef.length;i++) {
if(tabAnswer[p][i]==tabRef[i]) {
correctAndSameCase++;
}else if(tabAnswer[p][i]==tabRef[0] & tabAnswer[p][i]!=tabRef[i] || tabAnswer[p][i]==tabRef[1] & tabAnswer[p][i]!=tabRef[i] || tabAnswer[p][i]==tabRef[2]& tabAnswer[p][i]!=tabRef[i] ||tabAnswer[p][i]==tabRef[3] & tabAnswer[p][i]!=tabRef[i]) {
correctButDiffCase++;
}
}
index = 0;
p++;
System.out.println(correctAndSameCase+" number are on the same case on both arrays");
System.out.println(correctButDiffCase+" number are on different case on both arrays");
if(p>=3) {
p=0;
}
correctAndSameCase=0;
correctButDiffCase=0;
}
}
public static void main(String[] args) {
mainStack t= new mainStack();
}
Here for tabAnswer {5,4,3,2} correctAndSameCase should be 0 and correctButDiffCase should be 2 but in stead it gives me 0 and 1 as answer.
EDIT: I can see that the problem is in the condition to set the value to correctButDiffCasebut i don't know how to fix it
here a short code snippet that counts these two values.
But I didn't know, if you want to count some special cases (see TODOs).
public static void main(String[] args) throws Exception {
List<Integer> tabRef = Arrays.asList(10, 5, 3, 5, 2, 6);
List<Integer> tabRef2 = Arrays.asList(12, 8, 3, 5, 6, 2);
int matchesOnSameIndex = 0;
int matchesButDifferentIndex = 0;
for (int i = 0; i < tabRef.size(); i++) {
//compare on same index, if other list has element on this index
if (tabRef2.size() > i) {
if (tabRef.get(i) == tabRef2.get(i)) {
//same element on same index
matchesOnSameIndex++;
}
}
//check if value exists in other list
if (tabRef2.contains(tabRef.get(i))) {
//if yes, check if it is not at same position
if (tabRef2.size() > i) {
if (tabRef2.get(i) != tabRef.get(i)) {
//not same index
//TODO must count multiple times, if element exists multiple times?
matchesButDifferentIndex++;
}else {
//TODO must count, if also exists on other index?
}
}else {
//same position not existing, so must be on other position
matchesButDifferentIndex++;
}
}
}
System.out.println("matchesOnSameIndex: "+matchesOnSameIndex);
System.out.println("matchesButDifferentIndex: "+matchesButDifferentIndex);
}
your code to count the occurences seem fine (although a bit messy).
I wrote a junit test using your code and there is no issue:
#Test
public void testArrayCheck() {
int[] tabRef = {0,1,2,3};
int tabAnswer[][] = new int[3][4];
int[] tabAnswerPos0 = {0,0,0,0};
tabAnswer[0] = tabAnswerPos0;
int p = 0;
int correctAndSameCase = 0;
int correctButDiffCase = 0;
Set<Integer> setArrayValues = new HashSet<Integer>();
for(int i=0 ; i<tabRef.length;i++) {
if(tabAnswer[p][i]==tabRef[i]) {
correctAndSameCase++;
}else if(tabAnswer[p][i]==tabRef[0] && tabAnswer[p][i]!=tabRef[i]
|| tabAnswer[p][i]==tabRef[1] && tabAnswer[p][i]!=tabRef[i]
|| tabAnswer[p][i]==tabRef[2] && tabAnswer[p][i]!=tabRef[i]
||tabAnswer[p][i]==tabRef[3] && tabAnswer[p][i]!=tabRef[i]) {
if (!setArrayValues.contains(tabAnswer[p][i])) {
correctButDiffCase++;
setArrayValues.add(tabAnswer[p][i]);
}
}
}
System.out.println(correctAndSameCase+" number are on the same case on both arrays");
System.out.println(correctButDiffCase+" number are on different case on both arrays");
}
1 number are on the same case on both arrays
1 number are on different case on both arrays
Are you sure that tabAnswers has the values {5,4,3,2}?
import java.awt.Color;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Thresholdst {
public static void main(String[] args) {
int THRESHOLD = 111;
String filename = args[0];
Picture f = new Picture("C:\\Users\\User\\eclipse-workspace\\breakvisualcaptcha\\src\\breakvisualcaptcha\\2.png");
f.show();
for (int i = 0; i < f.width(); i++) {
for (int j = 0; j < f.height(); j++) {
Color color = f.get(i, j);
double lum = Luminance.intensity(color);
if (lum >= THRESHOLD) f.set(i, j, Color.WHITE);
else f.set(i, j, Color.BLACK);
}
}
f.show();
}
}
I am getting the error on the line:
Picture f = new Picture ("C:\\Users\\User\\eclipse-workspace\\breakvisualcaptcha\\src\\breakvisualcaptcha\\2.png");
Eclipse says:
Picture cannot be resolved to a type
I am using the header file import javax.imageio.ImageIO; then all the other lines following the File f line are getting highlighted. Please help me.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
how to write a Java class to sort 10 billion integers, assuming we can only fit a subset of them in memory at once.
I have done sorting but questions is how i would get the 1 billion values ?
How I am gonna sort them if i am going to load a portion of them in memory ?
If you can help me with source code it would be much appreciated.
Thanks in advance.
here is my last code, you can run it and guide me now.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
/**
* #project jqcontacts
* #date Mar 26, 2012
* #time 11:16:35 AM
*/
public class SortIntegers {
private static String BIG_FILE="g:/bigFile.txt";
private static String SORT_FILE_PREFIX = "g:/sortFile";
/*private static final int SORT_FILE_MAX_SIZE = 1000000;*/
private static final int SORT_FILE_MAX_SIZE = 10;
private static final String MAIN_FILE = "g:/rawfile1.txt";
private static int RAWA_FILE_MAX_SIZE = 100;
// if i keep the size of MERGE_BUFFER_INITIAL_SIZE = SORT_FILE_MAX_SIZE, the end big file is sorted.
private static int MERGE_BUFFER_INITIAL_SIZE=5;
private static int MERGE_BUFFER_SIZE_NEXT = MERGE_BUFFER_INITIAL_SIZE;
private static int MERGE_BUFFER_SIZE_PREVIOUS = 0;
private static int countFile = 0;
public static void readFile(String name) throws FileNotFoundException{
Scanner scanner = new Scanner(new File(name));
List<Integer> intList = new ArrayList<Integer>();
int fileSize = 0 ;
while(scanner.hasNextInt()){
intList.add(scanner.nextInt());
++fileSize;
if(fileSize>=SORT_FILE_MAX_SIZE){
Collections.sort(intList);
/*System.out.println("list size: " + intList.size());*/
String fileName = SORT_FILE_PREFIX + countFile +".txt";
++fileSize;
PrintWriter out = openWriter(fileName);
for(int i:intList){
writeFile(i, out);
}
out.close();
intList.clear();
++countFile;
fileSize = 0;
}
}
System.out.println("done!");
}
public static List<Integer> readSortFile(String name, List<Integer> list) throws FileNotFoundException{
Scanner scanner = new Scanner(new File(name));
int bufferSize = 0;
while(scanner.hasNextInt()){
++bufferSize;
if(bufferSize>=MERGE_BUFFER_SIZE_PREVIOUS && bufferSize<=MERGE_BUFFER_SIZE_NEXT){
list.add(scanner.nextInt());
}
if(bufferSize>=MERGE_BUFFER_SIZE_NEXT){
break;
}
}
Collections.sort(list);
return list;
}
private static PrintWriter openWriter(String name) {
try {
File file = new File(name);
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)), true);
return out;
} catch (IOException e) {
//System.out.println("I/O Error");
e.printStackTrace();
System.exit(0);
}
return null;
}
private static void writeFile(int i, PrintWriter out) {
/* String line = "0" + "\t" + Integer.toString(i);*/
String line = Integer.toString(i) + "\t";
out.println(line);
}
/**
* #param args
*/
public static void main(String[] args) {
generateRawIntFile();
try {
readFile(MAIN_FILE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("countFile: " + countFile);
// merge sort here, merge the sorted files into one
List<Integer> comboList = new ArrayList<Integer>();
boolean isDone = true;
PrintWriter outP = openWriter(BIG_FILE);
while(isDone){
for(int i=0;i<countFile;i++){
try {
//TODO: do we need the return type for readSortFile ????
comboList = readSortFile(SORT_FILE_PREFIX+i+".txt", comboList);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// System.out.println("hun writing on big file " + comboList.size());
// add the list into bigfile and clear it for further processing
try{
for(int value:comboList){
writeFile(value, outP);
}
comboList.clear();
MERGE_BUFFER_SIZE_PREVIOUS = MERGE_BUFFER_SIZE_NEXT;
MERGE_BUFFER_SIZE_NEXT += MERGE_BUFFER_INITIAL_SIZE;
System.out.println("MERGE_BUFFER_SIZE_PREVIOUS: " + MERGE_BUFFER_SIZE_PREVIOUS + " MERGE_BUFFER_SIZE_NEXT:" + MERGE_BUFFER_SIZE_NEXT);
if(MERGE_BUFFER_SIZE_PREVIOUS >= RAWA_FILE_MAX_SIZE){
System.out.println("sorting is finished");
isDone = false;
break;
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
*/
public static void generateRawIntFile() {
Random randomGenerator = new Random();
PrintWriter out = openWriter(MAIN_FILE);
for (Integer i = 0; i < RAWA_FILE_MAX_SIZE;i++){
Integer value = randomGenerator.nextInt(RAWA_FILE_MAX_SIZE);
writeFile(value, out);
}
out.close();
}
}
There are only 4 billion possible int values so the most efficient way of doing this, is to count the number of occurrences of any value. You can use a memory MappedByteBuffer so you don't have to have 16 GB of memory. Once you have counted all the occurrences the counts will naturally be in order, so no further sorting is required. The time complexity is O(n) instead of O(n * log n) line merge sort or quick sort.
import sun.nio.ch.DirectBuffer;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class Sort10Billion {
public static void main(String... args) throws IOException {
Runtime runtime = Runtime.getRuntime();
long used1 = runtime.totalMemory() - runtime.freeMemory();
MassiveCounterStore mcs = new MassiveCounterStore();
long start = System.nanoTime();
long count = 10 * 1000 * 1000 * 1000L;
for (long i = count; i > 0; i--)
mcs.incrementIndex((int) (i / 1019));
mcs.iterator(new NumberCountFunction() {
#Override
public void counted(int n, long count) {
// System.out.println(n + ": " + count);
}
});
long time = System.nanoTime() - start;
long used2 = runtime.totalMemory() - runtime.freeMemory();
System.out.printf("Took %.1f seconds to sort %,d numbers, using %.3f MB%n", time / 1e9, count, (used2-used1)/1e6);
mcs.close();
}
}
interface NumberCountFunction {
public void counted(int n, long count);
}
class MassiveCounterStore {
public static final int PARTITION_BITS = 26;
static final int PARTITIONS = (1 << (34 - PARTITION_BITS)); // 32-bit * 4 bytes.
final MappedByteBuffer[] buffers = new MappedByteBuffer[PARTITIONS];
final FileChannel channel;
int smallest = PARTITIONS;
int largest = 0;
public MassiveCounterStore() throws IOException {
File tmpStore = File.createTempFile("counter", "dat");
tmpStore.deleteOnExit();
channel = new RandomAccessFile(tmpStore, "rw").getChannel();
for (int i = 0; i < PARTITIONS; i++)
buffers[i] = channel.map(FileChannel.MapMode.READ_WRITE, (long) i << PARTITION_BITS, 1 << PARTITION_BITS);
}
public void incrementIndex(int n) {
long l = (n + Integer.MIN_VALUE) & 0xFFFFFFFFL;
int partition = (int) (l >> (PARTITION_BITS - 2)); // 4 bytes each.
int index = (int) ((l << 2) & ((1 << PARTITION_BITS) - 1));
MappedByteBuffer buffer = buffers[partition];
int count = buffer.getInt(index);
buffer.putInt(index, count + 1);
if (smallest > partition) smallest = partition;
if (largest < partition) largest = partition;
}
public void iterator(NumberCountFunction nfc) {
int n = (smallest << (PARTITION_BITS -2)) + Integer.MIN_VALUE;
for (int p = smallest; p <= largest; p++) {
MappedByteBuffer buffer = buffers[p];
for (int i = 0; i < 1 << PARTITION_BITS; i += 4) {
int count = buffer.getInt(i);
if (count != 0)
nfc.counted(n, count & 0xFFFFFFFFL);
n++;
}
}
assert n == Integer.MIN_VALUE;
}
public void close() {
try {
channel.close();
} catch (IOException ignored) {
}
for (MappedByteBuffer buffer : buffers) {
((DirectBuffer) buffer).cleaner().clean();
}
}
}
prints when run with -XX:-UseTLAB (which gives you more accurate memory usage)
Took 150.7 seconds to sort 10,000,000,000 numbers, using 0.202 MB
I think using 202 KB is pretty good. ;)
Note: your performance is heavily dependant on the distribution of values as this impacts the efficiency of the cache.
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();
}
}
}