Storing text file as 2D character array - java

I have a text file:
##########
#.......*#
#.########
#........#
########.#
##.......#
##########
How can I get this to be represented as a 2D character array like this:
char[][] maze = {{##########},
{#.......*#},
{#.########},
{#........#},
{########.#},
{##.......#},
{##########}};
I'm also using a JFileChooser to get the text file and saving it as a java.io.File.
Here's what I have that finds the rows/columns and attempts to store the text file as a 2D char array.
import javax.swing.*;
import java.io.*;
import java.util.*;
/**
* Created by marcusstone on 9/10/15.
*/
public class MazeReader {
public static int colNum;
public static int rowNum;
public static int levels;
public static File textFile;
public char[][] maze = new char[rowNum][colNum];
public int getRows() {
return rowNum;
}
public int getCols() {
return colNum;
}
public void loadFile() {
JFileChooser chooseFile = new JFileChooser();
if (chooseFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
textFile = chooseFile.getSelectedFile();
} else {
textFile = null;
}
}
public void getMazeInfo() {
try {
Scanner myScanner = new Scanner(textFile);
String firstLine = myScanner.nextLine();
colNum = firstLine.length();
rowNum = 1;
levels = 1;
while (myScanner.hasNextLine()) {
String aLine = myScanner.nextLine();
if (aLine.charAt(0) != '-') {
rowNum++;
}
if (aLine.charAt(0) == '-') {
levels++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void getMazeCharArray() throws IOException {
try {
BufferedReader reader = new BufferedReader(new FileReader(textFile));
String line = null;
int x = 0, y = 0;
//draw the maze
for(int i = 0; i < rowNum; i ++){
line = reader.readLine();
System.out.println(line);
}
//add elements to the maze array
for(int i = 0; i < rowNum; i++){
for(int j = 0; j < colNum; j++){
maze[i]=line.toCharArray();
}
}
}catch(IOException e) {
e.printStackTrace();
}
}
public static void main (String[] args) throws IOException {
MazeReader myMazeReader = new MazeReader();
myMazeReader.loadFile();
myMazeReader.getMazeInfo();
System.out.println(rowNum);
System.out.println(colNum);
myMazeReader.getMazeCharArray();
} // end main
} // end class

First you put some tried material, but nevertheless here:
First load file and read from that. Reading data, put into two -dimensional array, with x = y = your boundary,
char[x][y] maze;
.

Related

JAVA trying to read a file it sets nextChar equal to a box thing instead of the next char in the save file. where have I gone wrong?

this is a debugger error and runs an infinite loop where shown.
I am trying to load a file and have the gameboard be set to the chars in the text file (which are saved previously by user as shown) but in the debugger problem it sets next nextChar infinitely to □ after the first char has been read. I have had multiple attempts at trying to fix this myself but I cannot find a solution. Any help on how to fix this bug would be greatly appreciated. If any more details are needed give voice and see questions answered hastily.
This is the saving section of code.
/**
* A method to save the current state of the game
*/
public static void saveGame()
{
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
try
{
System.out.println("Please name the save game file.");
outputStream = new FileOutputStream(Genio.getString());
printWriter = new PrintWriter(outputStream);
int i, j =0;
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printWriter.println(gameBoard[i][j]);
}
}
}
catch (IOException e)
{
System.out.println("Sorry an error occured during saving.");
}
finally
{
if (printWriter != null)
{
printWriter.close();
}
}
}
This is the loading section of code;
/**
* A method to load a game.
*/
public static void loadGame()
{
FileReader fileReader = null;
BufferedReader bufferedReader = null;
char nextChar;
String line;
try
{
System.out.println("Please enter the name of your save file:");
fileReader = new FileReader(Genio.getString());
bufferedReader = new BufferedReader(fileReader);
nextChar = (char)bufferedReader.read();
while ((line = bufferedReader.readLine()) != null)
{
for (int i=0; i<row; i++)
{
for (int j=0; j<col; j++)
{
if (nextChar == '-' || nextChar == 'Y' || nextChar == 'R') //Infinite loop here where nextChar = □
{
gameBoard[i][j] = nextChar;
nextChar = (char)bufferedReader.read();
System.out.print(gameBoard[i][j]);
line = bufferedReader.readLine();
}
else
{
nextChar = (char)bufferedReader.read();
j--;
}
}
System.out.print("\n");
}
line = bufferedReader.readLine();
}
System.out.println("1\t2\t3\t4\t5\t6\t7");
}
catch (IOException e)
{
System.out.println("Sorry an error occured during the loading of the file.");
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException e)
{
System.out.println("Sorry, an error has occured when closing the file.");
}
}
}
}
Not sure why you are reading a line AND reading characters.
You need to read each line and process each character in that line, for example...
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ReadConnect4 {
private static final String TEST_BOARD = "-------\n"
+ "-------\n"
+ "-------\n"
+ "-------\n"
+ "-Y-----\n"
+ "-Y--R--\n";
private static final int ROWS = 6;
private static final int COLS = 7;
public static void main(String[] args) throws Exception {
ByteArrayInputStream pretendFile = new ByteArrayInputStream(TEST_BOARD.getBytes());
char[][] board = readBoard(pretendFile);
printBoard(board);
}
private static void printBoard(char[][] board) {
for(int k = 0; k < board.length; k++) {
for(int j = 0; j < board[k].length; j++) {
System.out.print(board[k][j]);
}
System.out.println();
}
}
private static char[][] readBoard(InputStream stream) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
int row = 0;
char[][] result = new char[ROWS][COLS];
// Read each line, stop when end of file (line is null)...
while((line = reader.readLine()) != null) {
// For each column...
for(int col = 0; col < 7; col++) {
// Get character from line, store in array
result[row][col] = line.charAt(col);
}
row++;
}
return result;
}
}
OUTPUT:
-------
-------
-------
-------
-Y-----
-Y--R--
To answer your question "why does it read box things", it's probably reading the end-of-stream and returning the character equivalent of "-1"

Why does my file get null in Java?

Trying to read in a maze in from a textfile to Java.
import java.io.*;
public class Maze {
private char[][]mazeData;
public static void main(String[] args) {
Maze test = new Maze();
}
public Maze() {
BufferedReader reader = null;
try {
File f = new File("c://testing.txt");
String line = null;
int row = 0;
reader = new BufferedReader(new FileReader(f));
reader.mark((int)f.length());
while ((line = reader.readLine()) != null) {
line = reader.readLine();
row++;
}
reader.reset();
mazeData = new char[row][];
row = 0;
while ((line = reader.readLine()) != null) {
mazeData[row++] = line.toCharArray();
}
int col=mazeData[0].length;
for (int i=0; i < row; i++){
for (int j=0; j < col; j++){
System.out.print(mazeData[i][j]);
}
System.out.println();
}
reader.close();
} catch (IOException e) {
System.out.println("INVALID FILE");
}
}
}
I tested in another class and java could find the file there so i dont get why the exeption keeps happening.
If you would print the catched exception you would read java.io.IOException: Mark invalid. Which is thrown at reader.reset(); because the mark has been invalidated.
You can fix it by
reader.mark((int)f.length() + 1);
Anyway there is no need to process the file twice only to know the number of lines. You can read all lines into a List<String> and process the lines from that array.
List<String> lines = Files.readAllLines(Paths.get("c:/testing.txt"),
Charset.defaultCharset());
edit
A stripped down solution (based on your code) could be.
public class Maze {
private char[][] mazeData;
public static void main(String[] args) {
Maze test = new Maze();
}
public Maze() {
try {
List<String> lines = Files.readAllLines(Paths.get("c:/testing.txt"), Charset.defaultCharset());
mazeData = new char[lines.size()][];
for (int i = 0; i < lines.size(); i++) {
mazeData[i] = lines.get(i).toCharArray();
}
int columns = mazeData[0].length;
int rows = lines.size();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(mazeData[i][j]);
}
System.out.println();
}
} catch (IOException ex) {
System.out.println("failed: " + ex.getMessage());
}
}
}
Keep few other comments:
- avoid to do I/O processing in a constructor
- split the code in logical blocks (one method per logical step), e.g. initMazed(), printMaze(), etc.

Printing a 2D array from the main method using exception handling

Hey so I've written some code to read the contents of a text file, do some comparisons and output either 1 or 0 into a 2D array. Here is a snippet
import java.io.*;
import java.util.*;
public class readFile
{
private String path;
//declare variables for visited and link
//String inputSearch1 = "Visited";
//String inputSearch2 = "Link";
String word;
public readFile(String pathname)
{
path = pathname;
}
//open the file and read it and search each line of the file for 'Visited' and 'Link'
public String[] OpenFile() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader lineReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] lineData = new String[numberOfLines];
int i;
for(i=0; i<numberOfLines; i++)
{
lineData[i] = lineReader.readLine();
}
lineReader.close();
return lineData;
}
//allows the file to be parsed without knowing the exact number of lines in it
int readLines() throws IOException
{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null)
{
numberOfLines++;
}
bf.close();
return numberOfLines;
}
int outLinks;
int inLinks;
String bLine;
String[] searchStrings() throws IOException
{
FileReader ftr = new FileReader(path);
BufferedReader bf2 = new BufferedReader(ftr);
int numberOfLines = readLines();
//String bLine;
String[] parseLine = new String[numberOfLines]; //array to store lines of text file
int[][] linkMatrix = new int[outLinks][inLinks]; //2d array to store the outLinks and inLinks
int i;
for(i=0; i<numberOfLines; i++)
{
parseLine[i] = bf2.readLine();
int j, k;
for(j=0; j<outLinks; j++)
{
for(k=0; k<inLinks;k++)
{
if(bLine.startsWith("Visited") && equals(bLine.startsWith("Link")))
{
linkMatrix[outLinks][inLinks] = 1;
}
else
{
linkMatrix[outLinks][inLinks] = 0;
}System.out.println(Arrays.deepToString(linkMatrix));
}//System.out.println();
}
}bf2.close();
return parseLine;
}
I am now trying to output this from the main method but each time I run it, all I get is the contents of the text file and no 2D matrix.
import java.io.IOException;
public class linkStatistics
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
//read file
String fileName = "C:\\Users\\Ikemesit\\Documents\\Lab_4.txt";
try
{
readFile file = new readFile(fileName);
//String[] lines = file.OpenFile();
String[] lines = file.searchStrings();
int i;
for(i=0;i<lines.length;i++)
{
System.out.println(lines[i]);
//System.out.println(lines2[i]);
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
Any help would be much appreciated! Thanks.
This condition has many problems :
if(bLine.startsWith("Visited") && equals(bLine.startsWith("Link")))
You never initialize bLine. This means that the condition would throws NullPointerException. I'm assuming you want to test the lines you read from the file instead.
equals makes no sense in this context - it compares your readFile instance with a boolean.
A line can't start with both prefixes, so you probably want || (OR) instead of && (AND).
I think this would make more sense :
if(parseLine[i].startsWith("Visited") || parseLine[i].startsWith("Link"))

Reading a file NoSuchElementException [closed]

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.
I am trying to read a file with doubles. I locate that problem occurs when I am trying to read decimal numbers. While in case of integers, everything work fine. I am receiving NoSuchElementException exception. Any idea about how to solve my problem? My code:
public class readd {
protected Formatter output;
protected Scanner input = new Scanner(System.in);
private Scanner in = new Scanner(System.in);
protected FileWriter out;
protected BufferedWriter out1;
private String ss;
public int r=1,c=1;
public double[][] output_matrix = null;
public double[][] output_matrix2 = null;
public double[] lap_time = null;
public readd() {
}
public void OpenFileRead(String fileName) { //anoigma tou arxeiou gia diavasma
try {
input = new Scanner(new File(fileName));
System.out.println(fileName);
} catch (FileNotFoundException e) { //sfalma kata tin evresi kai to anoigma tou arxeiou
System.err.println("Sfalma kata to anoigma toy arxeioy");
System.exit(0); //eksodos
}
}
public void Load() { //anagnwsi dedomenwn apo arxeio
// double[][] w1 = null;
int count = 0;
int row = 0, col = 0;
// double [][] w1=null;
try {
while (input.hasNext()) { //oso tha iparxei apothikeumeni eggrafi
count++;
if (count == 1) {
row = input.nextInt();
r = row;
// System.out.println(row);
continue;
} else if (count == 2) {
col = input.nextInt();
// System.out.println(col);
c = col;
continue;
} else {
// System.out.println("col="+col);
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
output_matrix[i][j] = input.nextDouble();
//String ss=new Integer(input.nextInt()).toString();
//w1[i][j]=Double.parseDouble(ss.trim());
// String s1 = new Integer(input.nextInt()).toString();
//double v = Double.parseDouble(s1.trim());
//String s2 = new Integer(input.nextInt()).toString();
//int s = Integer.parseInt(s2.trim());
// System.out.print(output_matrix[i][j]+" ");
}
// System.out.println(" ");
}
//System.out.print(col);
//System.out.print(row);
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
}
}
public static void main(String[] args) {
// TODO code application logic here
double[][] wa1;
readd w = new readd();
w.OpenFileRead("W1.txt");
w.Load();
wa1 = w.output_matrix;
}here
I'd also like some more information.
Generally:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/NoSuchElementException.html
It's the end of an enumerator.
There is an idea
Scanner sc = new Scanner("1.0");
sc.nextDouble();
sc.nextDouble();
throws java.util.NoSuchElementException
just as API Scanner.nextDouble says
* #throws NoSuchElementException if the input is exhausted
enter package read;
import java.util.*;
import java.io.File;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileWriter;
import java.io.FileNotFoundException;
/**
*
* #author zenitis
*/
public class readd {
protected Formatter output;
protected Scanner input = new Scanner(System.in);
private Scanner in = new Scanner(System.in);
protected FileWriter out;
protected BufferedWriter out1;
private String ss;
public int r=1,c=1;
public double[][] output_matrix = null;
public double[][] output_matrix2 = null;
public double[] lap_time = null;
public readd() {
}
public void OpenFileRead(String fileName) {
try {
input = new Scanner(new File(fileName));
System.out.println(fileName);
} catch (FileNotFoundException e) {
System.err.println("Sfalma kata to anoigma toy arxeioy");
System.exit(0);
}
}
public void Load() {
int count = 0;
int row = 0, col = 0;
try {
while (input.hasNext()) {
count++;
if (count == 1) {
row = input.nextInt();
r = row;
continue;
} else if (count == 2) {
col = input.nextInt();
c = col;
continue;
} else {
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
output_matrix[i][j] = input.nextDouble();
}
}
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
}
public static void main(String[] args) {
double[][] wa1;
readd w = new readd();
w.OpenFileRead("W1.txt");
w.Load();
wa1 = w.output_matrix;
}
}here
I dont understand i change dot with comma in my txt file and everything works!!

Cannnot find "Array Out of Bounds Exception" Java

I am creating a search engine that reads in a text file, and prints out a word that a user can search for. I'm currently creating an index of arrays to be searched for. More information can be found here: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html
When I run this program right now, I get an "Array Index Out of Bounds Exception"
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 43
at SearchEngine.main(SearchEngine.java:128)
Can anyone help debug?
import java.util.*;
import java.io.*;
public class SearchEngine {
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i<x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static int getNumOfDistinctWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int count = 0;
int i = 1;
while (scan.hasNext() && i<x.length) {
if (!x[i].equals(x[i-1])) {
count++;
}
i++;
}
scan.close();
return count;
}
public static void readInDistinctWords (String [] x, String [] y) {
int i = 1;
int k = 0;
while (i<x.length) {
if (!x[i].equals(x[i-1])) {
y[k] = x[i];
k++;
}
i++;
}
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
Main
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//System.out.println(NUM_WORDS);
String [] wordArray = new String[NUM_WORDS];
readInWords(input, wordArray);
Arrays.sort(wordArray);
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
String [] vocabArray = new String[NUM_DISTINCT_WORDS];
readInDistinctWords(wordArray, vocabArray);
System.out.println("Finished creating vocabArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String [] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[NUM_DISTINCT_WORDS][10];
int [] wordCountArray = new int[NUM_DISTINCT_WORDS];
int lineNum = 0;
while (lineNum<concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; i++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
for(int j = 0; j < invertedIndex[i].length; i++) {
should probably be
j++
not
i++
Update after your fix.
That means that Arrays.binarySearch(vocabArray, scan.next()) is not finding the item being searched for. You cannot assume that the vocabArray has the item you are searching for. You will need to add an if(... < 0) for the binarySearch call.

Categories