Reading a 2d array from a file in java - 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++;
}

Related

Manipulate this code so that it counts the # of digits in a file

I need to manipulate this code so that it will read the # of digits from a file.
I am honestly stumped on this one for some reason. Do i need to tokenize it first?
Thanks!
import java.io.*;
import java.util.*;
public class CountLetters {
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Synopsis: Java CountLetters inputFileName");
System.exit(1);
}
String line = null;
int numCount = 0;
try {
FileReader f = new FileReader(args[0]);
BufferedReader in = new BufferedReader(f);
while ((line = in.readLine()) != null) {
for (int k = 0; k < line.length(); ++k)
if (line.charAt(k) >= 0 && line.charAt(k) <= 9)
++numCount;
}
in.close();
f.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(numCount + " numbers in this file.");
} // main
} // CountNumbers
Use '' to indicate a char constant (you are comparing chars to ints), also I would suggest you use try-with-resources Statement to avoid explicit close calls and please avoid using one line loops without braces (unless you are using lambdas). Like
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Synopsis: Java CountLetters inputFileName");
System.exit(1);
}
String line = null;
int numCount = 0;
try (BufferedReader in = new BufferedReader(new FileReader(args[0]))) {
while ((line = in.readLine()) != null) {
for (int k = 0; k < line.length(); ++k) {
if ((line.charAt(k) >= '0' && line.charAt(k) <= '9')) {
++numCount;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(numCount + " numbers in this file.");
} // main
Also, you could use a regular expression to remove all non-digits (\\D) and add the length of the resulting String (which is all-digits). Like,
while ((line = in.readLine()) != null) {
numCount += line.replaceAll("\\D", "").length();
}
Use if(Charachter.isDigit(char)) replace char with each char, this will count each number, and I believe arabic numbers as well.

Is it possible to read data from file and store it into 2d Array,when we don't know the number of line in the file,in java

I have to read data from file Here is data and want plot a graph vs thick(column 1 in data) and alpha(column 3) for every model. Every model has 7 line data,the last that start with 0 not required. Here is my code. it works but i don't think it is good code.please, suggest me better way to do the same.
public class readFile {
public static int showLines(String fileName) {
String line;
int currentLineNo = 0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
//skipping the line that start with M, # and 0.
currentLineNo++;
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
return currentLineNo;
}
//Now we know the dimension of matrix, so storing data into matrix
public static void readData(String fileName,int numRow) {
String line;
String temp []=null;
String data [][]=new String[numRow][10];
int i=0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
temp=(line.trim().split("[.]"));
for (int j = 0; j<data[i].length; j++) {
data[i][j] =temp[j];
}
i++;
}
}
// Extract one column from 2d matrix
for (int j = 0; j <numRow; j=j+6) {
for (int j2=j; j2 <6+j; j2++) {
System.out.println(Double.parseDouble(data[j2][0])+"\t"+Double.parseDouble(data[j2][2]));
//6 element of every model, col1 and col3
// will add to dataset.
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
}
//Main Method
public static void main(String[] args) {
//System.out.println(showLines("rf.txt"));
readData("rf.txt",showLines("rf.txt") );
}
}
as johnchen902 implies use a list
List<String> input=new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
input.add(line);
}
br.close();
int N=input.get(0).split(",").size(); // here add your delimiter
int M=input.size();
String[][] data=new String[M][N]
for (int i=0;i<M;i++){
String[] parts = string.split("-");
for (int k=0;k<n;k++){
data[i][k]=parts[k];
}
}
something like that
hope it helps. plz put more effort into asking the question. Give us the needed Input files, and the Code you came up with until now to solve the problem yourself.

Reading from a certain line until there is no more content in Java

I would like to read and display the content of a text file from a set line(In this case line 13) until the end of the text file.
So if the document has 20 lines, it should display line 13 to 20. The problem is, that this document gets more content and therefore the number of lines should be determined automatically.
Basically it needs to end when there is no more content. If I do not set an end line, the output is "null" forever.
try {
BufferedReader in = new BufferedReader (new FileReader("C://Users/Prakt1/Desktop/projektverwaltung.txt"));
String info = "";
int startLine = 13;
int endLine = 25;
System.out.println("");
for (int x = 0; x < startLine; x++) {
info = in.readLine();
}
for (int x = startLine; x < endLine + 1; x++) {
info = in.readLine();
System.out.println(info);
}
System.out.println("");
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
Thanks a lot for your help!
Use something like this to setup a loop. It will continue to read until it encounters a null, which would be the end of the file.
while ((info = in.readLine()) != null)
If I understand your question, you could do it with something like this -
for (int x = 0; x < startLine; x++) {
info = in.readLine();
}
while ((info = in.readLine()) != null) {
System.out.println(info);
}
Something like this should work:
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader("C://Users/Prakt1/Desktop/projektverwaltung.txt"));
String info = null;
int startLine = 13;
int lineNum = 0;
while ((info = in.readLine()) != null) {
lineNum++;
if (lineNum >= startLine) {
System.out.println(info);
}
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
in.close();
}
Also, be sure to close the reader in a finally block.
You may also want to look a LineNumberReader

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

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

Categories