Why does my file get null in Java? - 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.

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"

Java - store elements of ArrayList into separate blocks

so here is ALL of my code, which, in summary, standardises two text files then prints out the result.
import java.io.*;
import java.util.*;
public class Plagiarism {
public static void main(String[] args) {
Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
for (int i = 0; i < args.length; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
List<String> foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
System.out.print(foo.get(j));
}
}
}
catch (Exception e) {
System.err.println ("Error reading from file");
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
myList.add(line.replaceAll("[^a-zA-Z0-9]","").toLowerCase().trim());
}
return myList;
}
}
The next bit I want to implement is this: Using the command line, the 3rd argument will be any integer(size of blocks) which the user enters. I have to use this then to store the elements of that array into separate blocks which overlap. EG: The cat sat on the mat, block size 4. Block 1 would be: Thec Block 2: heca Block 3: ecat, and so on, until it reaches the end of the array.
Any ideas?
Thanks in advance guys.
To get the block size use this :
if(args.length != 4)
return;
int blockSize = Integer.valueOf(args[3]);
This an example that could help you
import java.util.*;
public class Test {
public static void main(String[] args) {
String line = "The dog is in the house";
line = line.replace(" ", "");
List<String> list = new ArrayList<String>();
for (int i = 0; i <= line.length() - 4; i++)
list.add(line.substring(i, i + 4));
System.out.println(list);
}
output :
[Thed, hedo, edog, dogi, ogis, gisi, isin, sint, inth, nthe, theh, heho, ehou, hous, ouse]
Is that what you want to do
WE can code it in mulitple ways, here is one example.
Input 3 arguments first 2 are files and 3rd one is the block size:
File1 contain: this is a boy
File2 contain: this is a girl
block size: 4
Expected Output:
this hisi isis sisa isab sabo aboy boyt oyth ythi this hisi isis sisa isag sagi agir girl
Program:
import java.io.;
import java.util.;
public class Plagiarism {
public static void main(String[] args) {
//Plagiarism myPlag = new Plagiarism();
/*args = new String[3];
Scanner s = new Scanner(System.in);
System.out.println("Enter the 1st file path");
args[0] = s.next();
System.out.println("Enter the 2nd file path");
args[1] = s.next();
System.out.println("Enter size of block");
args[2] = s.next();*/
int blockSize = Integer.valueOf(args[2]);
StringBuilder wholeContent = new StringBuilder("");
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
for (int i = 0; i < args.length-1; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
List<String> foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
//System.out.print(foo.get(j));
wholeContent.append(foo.get(j));
}
}
System.out.println("The content of Line is = "+ wholeContent);
System.out.println("The content of line based on the block size = "+ blockSize + " is:");
for(int j=0; j<=(wholeContent.length()-blockSize); j++){
System.out.print(wholeContent.substring(j, j+4));
System.out.print(" ");
}
}
catch (Exception e) {
e.printStackTrace();
System.err.println ("Error reading from file");
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
if(!" ".equals(line))
myList.add(line.replaceAll("[^a-zA-Z0-9]","").toLowerCase().trim());
}
return myList;
}
}
All you are asking to do can be done with string manipulation. First use replaceAll() to remove your spaces, then use a for loop and substring() to create your blocks.
for your for loop you need to modify it so that it reads the two texts, then uses the 3rd argument as the block size so you would change your for loop from:
for(int i = 0; i<args.length;i++)
to:
for(int i = 1; i<3; i++)
this reads the first two arguments but not the third

Java HashMap size limit? Some keys are disappearing in Bigram Frequency Count

I am writing a simple bigram frequency count algorithm in Java and encountering a problem I don't know how to fix.
My source file is a 9MB .txt file with random words, separated by spaces.
When I run the script limiting the input to the first 100 lines, I get a value of 1 for the frequency of the bigram "hey there".
But when I remove the restriction to only scan the first 100 lines and instead scan the entire file, I get a value of null for the same bigram search. The key/value pair in the HashMap is now null.
I am storing all the bigrams in a HashMap, and using a BufferedReader to read the text file.
What is causing the bigram (key) to be removed from or overwritten in the HashMap? It shouldn't matter if I am reading the entire file or just the first part of it.
public class WordCount {
public static ArrayList<String> words = new ArrayList<String>();
public static Map<String, Integer> bi_count = new HashMap<String, Integer>();
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(args[0]));
System.out.println("\nProcessing file...");
while (br.readLine() != null) {
// for (int i = 0; i < 53; i++ ) {
sCurrentLine = br.readLine();
if (sCurrentLine != null) {
String[] input_words = sCurrentLine.split("\\s+");
for (int j = 0; j < input_words.length; j++) {
words.add(input_words[j]);
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
countWords();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static void countWords() {
for (int k = 0; k < words.size(); k++) {
String word = words.get(k);
String next = "";
if (k != words.size() - 1) {
next = words.get(k+1);
}
String two_word = word + " " + next;
if (bi_count.containsKey(two_word)) {
int current_count = bi_count.get(two_word);
bi_count.put (two_word, current_count + 1);
}
else {
bi_count.put( two_word, 1);
}
}
System.out.println("File processed successfully.\n");
}
I'm not totally confident this is the cause of your problem, bot you are not reading all lines of your input file.
while (br.readLine() != null) {
sCurrentLine = br.readLine();
The line read in the if() statement is not being processed at all - you are missing alternate lines.
Instead try this:
while ((sCurrentline = nr.readLine()) != null) {
//now use sCurrentLine...
}
This block of code is wrong because readline is called twice:
while (br.readLine() != null) {
// for (int i = 0; i < 53; i++ ) {
sCurrentLine = br.readLine();
if (sCurrentLine != null) {
String[] input_words = sCurrentLine.split("\\s+");
for (int j = 0; j < input_words.length; j++) {
words.add(input_words[j]);
}
}
}
I would suggest:
while ((sCurrentline = nr.readLine()) != null) {
String[] input_words = sCurrentLine.split("\\s+");
for (int j = 0; j < input_words.length; j++) {
words.add(input_words[j]);
}
}

How do you store each value separately using comma then they store into separate array?

A simple data file which contains
1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
Each line represents a season of premiership and has the following format: year, premiers, runners up, minor premiers, wooden spooners, Grand Final held, winning score,
losing score, crowd
I know how to store a data into an array and use the delimiter, but I am not exactly sure how to store EACH data item by a comma into separate arrays? Some suggestions and what particular code to be used would be nice.
UPDATE:
I just added the code but it still didn't work. Here's the code:
import java.io.*;
import java.util.Scanner;
public class GrandFinal {
public static Scanner file;
public static String[] array = new String[1000];
public static void main(String[] args) throws FileNotFoundException {
File myfile = new File("NRLdata.txt");
file = new Scanner (myfile);
Scanner s = file.useDelimiter(",");
int i = 0;
while (s.hasNext()) {
i++;
array[i] = s.next();
}
for(int j=0; j<array.length; j++) {
if(array[j] == null)
;
else if(array[j].contains("Y"))
System.out.println(array[j] + " ");
}
}
}
Here you go. Use ArrayList. Its dynamic and convenient.
BufferedReader br = null;
ArrayList<String> al = new ArrayList();
String line = "";
try {
br = new BufferedReader(new FileReader("NRLdata.txt"));
while ((line = br.readLine()) != null) {
al.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
What does not work in your case ?
Because your season array is empty. You need to define the length, for ex:
private static String[] season = new String[5];
This is not right because you don't know how many lines you are going to store. Which is why I suggested you to Use ArrayList.
After working around a bit, I have come up with following code:
private static File file;
private static BufferedReader counterReader = null;
private static BufferedReader fileReader = null;
public static void main(String[] args) {
try {
file = new File("C:\\Users\\rohitd\\Desktop\\NRLdata.txt");
counterReader = new BufferedReader(new FileReader(file));
int numberOfLine = 0;
String line = null;
try {
while ((line = counterReader.readLine()) != null) {
numberOfLine++;
}
String[][] storeAnswer = new String[9][numberOfLine];
int counter = 0;
fileReader = new BufferedReader(new FileReader(file));
while ((line = fileReader.readLine()) != null) {
String[] temp = line.split(",");
for (int j = 0; j < temp.length; j++) {
storeAnswer[j][counter] = temp[j];
System.out.println(storeAnswer[j][counter]);
}
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
I have added counterReader and fileReader; which are used for counting number of lines and then reading the actual lines. The storeAnswer 2d array contains the information you need.
I hope the answer is better now.

Cannot find symbol 2d array return issue

I am trying to create a 2d array using the contents of a text file, however I am unable to return it. It says it cannot find the symbol firstDimension, however I declared it within the method.
import java.io.*;
import java.util.*;
public class Map {
public static char[][] readFile() {
try {
List<String> list = new ArrayList<String>();
String thisLine = null;
BufferedReader br;
br = new BufferedReader(new FileReader("map.txt"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
char[][] firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i=0; i < firstDimension.length; i++) {
for (int j=0; j < firstDimension[i].length; j++) {
System.out.print(firstDimension[i][j]);
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
return firstDimension;
}
}
firstDimension is declared within your try block hence its scope is that try block. to be able to return it outside the try block, you need to declare it as follows:
public static char[][] readFile() {
char[][] firstDimension = null;
try {
List<String> list = new ArrayList<String>();
String thisLine = null;
BufferedReader br;
br = new BufferedReader(new FileReader("map.txt"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i=0; i < firstDimension.length; i++) {
for (int j=0; j < firstDimension[i].length; j++) {
System.out.print(firstDimension[i][j]);
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
return firstDimension;
}
In that case, if an exception is encountered, your method could return null.
This is another example of the same issue.

Categories