Why isn't my array filled correctly? - java

I am writing code for a game in Java. Specificly I'm working on the level creation using a character array filled by characters from a .txt file. My problem is that the array is not filled as it should be and the final line remains empty. I can't work this out so any kind of help will be gladly accepted, here's the problematic block of code :
public static void main(String[] args) throws IOException{
char background[][] = new char [14][20];
try {
FileInputStream fileinput = new FileInputStream("background.txt");
int r;
for(int i=0;i<=13;i++){
for(int j=0;j<19;j++){
while((r = fileinput.read()) != -1){
char c = (char) r;
background[i][j] = c;
break;
}
}
}
fileinput.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i=0;i<=13;i++){
for(int j=0;j<=19;j++){
System.out.print(background[i][j]);
}
}
}
Also the code as a whole can be found in the following link: http://pastebin.com/HtwMpsjm
Here's the .txt file too!

You accidentally one of your conditions, i've commented on the changed line.
As someone has mentioned in the comments, you might find it beneficial to treat your loops conditions as for(int i=0;i<20;i++) rather than for(int i=0i<=19;i++) it makes the code a little more readable.
public static void main(String[] args) throws IOException{
char background[][] = new char [14][20];
try {
FileInputStream fileinput = new FileInputStream("background.txt");
int r;
for(int i=0;i<=13;i++){
for(int j=0;j<=19;j++){//<<THIS LINE WAS CHANGED
while((r = fileinput.read()) != -1){
char c = (char) r;
background[i][j] = c;
break;
}
}
}
fileinput.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i=0;i<=13;i++){
for(int j=0;j<=19;j++){
System.out.print(background[i][j]);
}
}
}

Why do we need multiple for loops here. If you want to read characters from a file you could use buffered reader and the this matrix could be created in one line of code like while((bufferedReader.read(background[i]) != -1) && (++i < 14)){ }. Also you are using a while loop to read one char and then an unconditional break statment inside is not a good practice (in my opinion). Try
public static void main(String[] args) throws IOException {
char background[][] = new char[14][20];
try {
FileReader fileReader = new FileReader("background.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
int i=0;
while((bufferedReader.read(background[i]) != -1) && (++i < 14)){ } // This like created your 2D array
bufferedReader.close();
fileReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i <= 13; i++) {
for (int j = 0; j <= 19; j++) {
System.out.print(background[i][j]);
}
}
}

Related

Java get all class and id names from css file

I am trying to get all the classes and ids from a css file in arrays. the arrays should look like this:
UsedIds: {"#id1, "#id2" etc.etc.etc.}
UsedClasses: {".class1", ".class2" etc.etc.etc.}
how do i get these results without getting the stuff with "." inside the curly braces? I tried to remove every "{code inside}" segment but there are mediaqueries and stuff conflicting with it. My first attempt is below here, but i am not proud of it... It only removes the curly codes, but i'm stuck with this right now. Do you guys know a easier solution?
private void getCssClasses(String fileName) {
File cssFile = new File(fileName);
Scanner sc;
try {
sc = new Scanner(cssFile);
while (sc.hasNextLine()) {
String cssLine = sc.nextLine();
int firstCurly = 0;
int lastCurly = 0;
while (cssLine.contains("{")) {
for (int i = 0; i < cssLine.length(); i++) {
String character = "" + cssLine.charAt(i);
//System.out.println(character);
if (character.contains("{")) {
//System.out.println("IN");
firstCurly = i;
}
if (character.contains("}")) {
if(firstCurly != 0){
System.out.println("OUT");
lastCurly = i;
}
}
if (firstCurly != 0 && lastCurly != 0) {
StringBuilder sb = new StringBuilder(cssLine);
sb.delete(firstCurly, lastCurly);
cssLine = sb.toString();
System.out.println("YES");
break;
}
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

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"

want to print a data according to row in text file

I have a text file of data like this
username=Ayyappa,password=123
username=venkata,password=456
username=Bhargav,password=789
username=Rama,password=158
username=Pusarla,password=968
i want to print the data at row number 2
(My expected output is username=venkata,password=456)
Funtion written:
public class TestDataReader {
public static String getrowvalue(String FileName, int rownum) throws IOException{
FileReader fr = new FileReader(FileName);
BufferedReader br = new BufferedReader(fr);
String lineString = null;
while((lineString = br.readLine())!= null){
int counter = 1;
if(counter == rownum){
System.out.println(lineString);
counter ++;
}
}
return lineString;
}
}
i called this function in another class
TestDataReader.getrowvalue("F:\WS_Finsys_Ayyappa\Ejagruti\TestData\login.txt", 2);
but when i am calling this function it is printing all the row data but not with row data i passed in this case i passed rownum 2 to get the row data
Your mistake is here: you simply flush counter value each time in loop:
int counter = 1;
So change it to:
int counter = 1;
while((lineString = br.readLine())!= null){
if(counter == rownum){
System.out.println(lineString);
}
counter++;
}
UPD: Also, as #Lemm Ras mentioned, you have to move counter incrementation outside if statement.
Java 8 solution:
For small files:
String line32 = Files.readAllLines(Paths.get("file.txt")).get(32)
For large files:
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
line32 = lines.skip(31).findFirst().get();
}
A simple one ,Java <8 solution:
public String readLine(int line){
FileReader tempFileReader = null;
BufferedReader tempBufferedReader = null;
try { tempFileReader = new FileReader(textFile);
tempBufferedReader = new BufferedReader(tempFileReader);
} catch (Exception e) { }
String returnStr = "ERROR";
for(int i = 0; i < line - 1; i++){
try { tempBufferedReader.readLine(); } catch (Exception e) { }
}
try { returnStr = tempBufferedReader.readLine(); } catch (Exception e) { }
return returnStr;
}

Reading a 2d array from a file in java

I have a text file that is 32x32 in size. For example first two lines:
11111111111111111111111111111111
11111111111111111111111111111000
...
I want to read and store this file in a 2D array. I have the following java code, but can't exactly figure out how to read the file data. I guess I would need two nested for loops?
public static int[][] readFile(){
BufferedReader br = null;
int[][] matrix = new int[32][32];
try {
String thisLine;
int count = 0;
br = new BufferedReader(new FileReader("C:\\input.txt"));
while ((thisLine = br.readLine()) != null) {
//two nested for loops here? not sure how to actually read the data
count++;
}
return matrix;
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return matrix;
}
Assuming that each line in your file is a row, and, for each row, a character is an entry:
// ...
int i,j;
i = 0;
while((thisLine = br.readLine()) != null) {
for(j = 0; j < thisLine.lenght(); j++) {
matrix[i][j] = Character.getNumericValue(thisLine.charAt(j));
}
i++;
}
// ...
This is just a starting point... there may be many more efficient and clean ways to do this, but now you have the idea.
You only need one more loop, since the while loop you already have is functioning as the outer loop.
while ((thisLine = br.readLine()) != null) {
for(int i = 0; i < thisLine.length(); i++){
matrix[count][i] = Character.getNumericValue(thisLine.charAt(i));;
}
count++;
}

swap first and last column of a 2D array in a text file in java

Input file-
5
1 2 3 4 5
2 3 4 5 6
3 2 1 5 8
My work is i should read this input file my.txt and swap its first and last column and output it to another file comp.txt but I am getting a blank file comp.txt
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintStream;
import java.io.*;
// to swap first and last column of 2D array
public class Swap
{
private static BufferedReader in = null;
private static int row = 0;
private static int column = 0;
private static int[][] matrix = null;
public static void main(String[] args) throws Exception
{
try
{
// String filepath = args[0];
int lineNum = 0;
int row = 0;
in = new BufferedReader(new FileReader("my.txt"));
String line = null;
while ((line = in.readLine()) != null)
{
lineNum++;
if (lineNum == 1)
{
column = Integer.parseInt(line);
}
else
{
String[] tokens = line.split(",");
for (int j = 0; j < tokens.length; j++)
{
if (j == 0) matrix[row][0] = Integer.parseInt(tokens[column]);
else matrix[row][j] = Integer.parseInt(tokens[j]);
}
row++;
}
}
}
catch (Exception ex)
{
System.out.println("The code throws an exception");
System.out.println(ex.getMessage());
}
finally
{
if (in != null) in.close();
}
try
{
PrintStream output = new PrintStream(new File("comp.txt"));
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
output.println(matrix[i][j] + " ");
}
}
output.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Here is the output I am getting at console-
The code throws an exception
null
Apart from this I am getting a blank comp.txt file
After I replaced your catch block with
catch (Exception ex)
{
System.out.println("The code throws an exception");
System.out.println(ex.getMessage());
ex.printStackTrace();
}
I could tell that the error is
java.lang.NullPointerException
at test.example.code.Swap.main(Swap.java:37)
The code throws an exception
null
Where the line is
if (j == 0) matrix[row][0] = Integer.parseInt(tokens[column]);
Because you are trying to access the 5th column of tokens but it's actually a 5-length array and indices in Java and most C-based languages in general are zero-indiced aka the valid indices are from 0 to 4.
Also, I'm not entirely sure what you are trying to do with this line, so I won't fix it, but that's the error.
EDIT:
Now this is not exactly a legitimate thing to do, but I solved it as I would have done it myself, and I will explain it afterwards. If you mustn't read the code because your "mentor" would be against it, then just read the final lines of this post and solve it on your own.
// to swap first and last column of 2D array
public class Swap
{
private static BufferedReader in = null;
private static int column = 0;
private static List<int[]> matrix = null;
public static void main(String[] args) throws Exception
{
try
{
// String filepath = args[0];
in = new BufferedReader(new FileReader("my.txt"));
String line = null;
matrix = new ArrayList<int[]>(); //array length is variable length
//so using a 2D array without knowing the row size is not right
boolean isFirstLine = true;
while ((line = in.readLine()) != null)
{
if (isFirstLine)
{
column = Integer.parseInt(line); //first line determines column length
isFirstLine = false;
}
else
{
String[] tokens = line.split(" "); // there are no commas in input file so split on spaces instead
matrix.add(new int[column]);
for (int i = 0; i < tokens.length; i++)
{
matrix.get(matrix.size() - 1)[i] = Integer.parseInt(tokens[i]);
//store the lines of the currently read line in the latest added array of the list
}
}
}
}
catch (Exception ex)
{
System.out.println("The code throws an exception");
ex.printStackTrace(); //changed exception write out for better info
}
finally
{
if (in != null)
in.close();
}
// swapping the elements of first and last in each int array of list
for(int[] intLines : matrix)
{
int temp = intLines[0];
intLines[0] = intLines[intLines.length-1];
intLines[intLines.length-1] = temp;
}
BufferedWriter output = null;
try
{
output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(
"comp.txt")))); //i just prefer bufferedwriters don't mind me
output.write("" + column); //write the first line that is the array length into file
output.newLine();
for (int[] intLines : matrix) //write out each line into file
{
for (int i = 0; i < intLines.length; i++)
{
output.write("" + intLines[i]);
if (i < (intLines.length - 1))
{
output.write(" ");
}
}
output.newLine();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if (output != null)
{
try
{
output.close();
}
catch (IOException e)
{
}
}
}
}
}
So basically I changed the 2D array to a list of arrays, read in the file, fixed that you were splitting along commas instead of spaces, and actually did the swap. You don't necessarily have to take this approach, especially if that is against the rules. Don't even read the code if you mustn't.
1) Change
System.out.println("The code throws an exception");
System.out.println(ex.getMessage());
To get detailed description for cause of exception.
System.out.println("The code throws an exception");
ex.printStackTrace();
2) From code & exception message it seems like there is a NullPointerException as ur array matrix is initialized to null and not to array of matching size.
So solution to the exception is[Assuming your core logic is fine] , before assigning any values to matrix array, initialize with relevant size i.e with max rows & columns

Categories