Doesn't save the words in array - java

i've got a propably simple question. I try to read the file and i want to add each single word to my array "phrase". The problem occures in for loop. I got the exception "index 0 out of bounds for length 0".
Can you please help me with that?
String [] tokens;
String line;
String hash = " ";
int n = 0;
String [] phrase = new String [n];
public void loadFile()
{
try
{
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader("z3data1.txt"));
while((line = br.readLine()) != null)
{
tokens = line.split("[ ]");
n += tokens.length;
}
for(int j = 0; j<tokens.length; j++)
{
phrase[j] = tokens[j];
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}

A couple observations.
you are getting the error because your array is not large enough and the index j is exceeding its size.
you keep overwriting tokens in the while loop. The while loop needs to encompass the copying of the tokens to the phrase array.
So try the following:
while((line = br.readLine()) != null) {
tokens = line.split("[ ]");
n += tokens.length; // don't really need this.
//starting offset to write into phrase
int len = phrase.length;
phrase = Arrays.copyOf(phrase,phrase.length + tokens.length);
for(int j = 0; j<tokens.length; j++) {
phrase[j + len] = tokens[j];
}
}
This statement
phrase = Arrays.copyOf(phrase,phrase.length + tokens.length)
Copies the contents of phrase and increases the array size to handle the writing of tokens.
Another (and probably preferred) alternative is to use a List<String> which grows as you need it.
List<String> phrase = new ArrayList<>();
for(int j = 0; j<tokens.length; j++) {
phrase.add(tokens[j]);
}
// or skip the loop and just do
Collections.addAll(phrase,tokens);
One observation. I don't know what you are splitting on but your split statement looks suspicious.

You're setting n to 0, so phrase is also of length 0 when you say String[] phrase = String[n]. Therefore, you can't add anything to it.
If you want something of variable length, you can use an ArrayList. In the code below, you can directly use Collections.addAll to split up the line and put everything into the phrase ArrayList.
String line;
//Note that you can get rid of tokens here, since it's being inlined below
ArrayList<String> phrase = new ArrayList<>();
public void loadFile()
{
try
{
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader("z3data1.txt"));
while((line = br.readLine()) != null)
{
//No need for a for-loop below, you can do everything in one line
Collections.addAll(phrase, line.split("[ ]"));
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}

Related

In Java how to check if the next record in a file is the end?

I want to sequentially read each line of an input unsorted file into consecutive elements of the array until there are no more records in
the file or until the input size is reached, whichever occurs first. but i can't think of a way to check the next line if its the end of the file?
This is my code:
Scanner cin = new Scanner(System.in);
System.out.print("Max number of items: ");
int max = cin.nextInt();
String[] input = new String[max];
try {
BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"));
for(int i=0; i<max; i++){ //to do:check for empty record
input[i] = br.readLine();
}
}
catch (IOException e){
System.out.print(e.getMessage());
}
for(int i=0; i<input.length; i++){
System.out.println((i+1)+" "+input[i]);
}
the file has 205 lines, if I input 210 as max, the array prints with five null elements like so..
..204 Seychelles
205 Algeria
206 null
207 null
208 null
209 null
210 null
Thanks for your responses in advance!
From the docs:
public String readLine()
Returns: A String containing the contents of the line, not including
any line-termination characters, or null if the end of the stream has
been reached
In other words, you should do
String aux = br.readLine();
if(aux == null)
break;
input.add(aux)
I recomend you use a variable-size array (you can pre-allocated with the requested size if reasonable). Such that you get either the expected size or the actual number of lines, and can check later.
(depending on how long your file is, you might want to look at readAllLines() too.)
Please refer this Number of lines in a file in Java and modify your for loop to take whatever is the least out of the entered max value or the no.of lines in the file.
Use List<String>
List<String> lines = new ArrayList<>(); // Growing array.
try (BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"))) {
for(;;) {
String line = br.readLine();
if (line == null) {
break;
}
lines.add(line);
}
} catch (IOException e) {
System.out.print(e.getMessage());
} // Closes automatically.
// If lines wanted as array:
String[] input = lines.toArray(new String[lines.size()]);
Using a dynamically growing ArrayList is the normal way to deal with such problem.
P.S.
FileReader will read in the current platform encoding, i.e. a local file, created locally.
You could do a null check in your first for-loop like:
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
System.out.print("Max number of items: ");
int max = cin.nextInt();
BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"));
List<String> input = new ArrayList<>();
String nextString;
int i;
for (i = 0; i < max && ((nextString = br.readline()) != null); i++) {
input.add(nextString);
}
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + " " + input.get(j));
}
}
Try :
for(int i=0; i<max; i++){ //to do:check for empty record
if(br.readLine()!=null)
input[i] = br.readLine();
else
break;
}
int i=0;
for(; i<max; i++){ //to do:check for empty record
String line=br.readLine();
if(line==null){
break;
}
input[i] = line;
}
//i will contain the count of lines read. indexes 0...(i-1) represent the data.

Split file having Integers and string into strings only

i have the file which has data stored as " Integer-> \t(tab)-> String ->couple of space-> ".
Am I doing Wrong?
What I am doing is.
Trie t = new Trie();
BufferedReader bReader = new BufferedReader(new FileReader(
"H:\\100kfound.txt"));
String line;
String[] s = null;
while ((line = bReader.readLine()) != null) {
s = line.split("\t");
}
int i;
for (i = 0; i < s.length; i++) {
System.out.println(s[i]);
if (!(s[i].matches("\\d+"))) {
t.addWord(s[i]);
System.out.println(s[i]);
}
}
What I can see by debugging it is going properly till while loop but in for loop it just stores two strings and prints the same.
You might want to and a ^[0-9]+$ for the expressions so you just get complete integers. Without the ^ and $ you could be matching other characters like tt55gh would match.
if (!(s[i].matches("^[0-9]+$"))) {
}
Per the comment above you need to move the for loop inside the while loop.
while ((line = bReader.readLine()) != null) {
s = line.split("\t");
for (int i = 0; i < s.length; i++) {
System.out.println("Value "+i+": "+s[i]);
if (!(s[i].matches("^[0-9]+$"))) {
t.addWord(s[i]);
System.out.println("Integer "+i+": "+s[i]);
}
}
}

Trying to find the nth element to the last from a list (with a file input)

Input would look like
a b c d 4
e f g h 2
where each line would be read like a list and integer representing as an index in the list
I first try to read the file line be line and store it in the list. Heres what i have
public class FileReader {
public static void main(String[] args) {
String line = null;
List<String> list = new ArrayList<String>();
try {
FileInputStream fstream = new FileInputStream("test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// File file = new File("test.txt");
// Scanner scanner = new Scanner(file);
while ((line = br.readLine()) != null) {
list.add(line);
}
System.out.println(list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now i want to remove the white spaces from the list and store the values in char array and then i was planning on traversing that array backwards till the nth element, depending on the input for n.
String[] elements = line.trim().split("\\s");
char[] chars = new char[elements.length - 1];
int i= Integer.parseInt(elements[elements.length - 1]);
for (i = 0; i < elements.length - 1; i++)
char[i] = elements[i].charAt(i);
Someone provided me this piece of code earlier and i tried it and it throws a nullpointerexception at String[] elements.
It's because you are running until line is null here
while((line = br.readLine()) != null)
{
list.add(line);
}
And then you are trying to call .trim() on it.
Do you mean to be processing the strings in list instead?
If so try looping over you list, you are already splitting it correctly and getting the last element. All you need to do is caluclate the offset, in this case it will be the length - 1 - the last element, in you String[] elements and you can print that out.
for (int i = 0; i < list.size(); i++)
{
String currentLine = list.get(i);
String[] elements = currentLine.trim().split("\\s");
int lastElement = Integer.parseInt(elements[elements.length - 1]);
String desiredValue = elements[elements.length - 1 - lastElement];
System.out.println("desiredValue = " + desiredValue);
}
You can avoid most of the work you're doing. I don't know if your input will require much flexibility (code to that if necessary) but in your example you only have 1 digit for the index.
Just avoid all the traversing and looping entirely:
String currentLine = file.nextLine();
//Find value from last space in the string, until the end of the string (will be the number)
int index = Integer.parseInt(currentLine.substring(
currentLine.lastIndexOf(' ') + 1, currentLine.length()));
//Remove all spaces from the current line
currentLine = currentLine.replaceAll("\\s+","");
//Remove the index at the end from the string, leaving only the characters
currentLine = currentLine.substring(0, currentLine.indexOf(index + ""));
char desiredValue = currentLine.charAt(currentLine.length() - index);
System.out.println("desiredValue = " + desiredValue);
This saves a lot of adding stuff to arrays if none of that is needed later, just do it all the first time through.

Importing data from a large file into a 2d Array

I am trying to import a large data file and insert the information into a 2D array. The file has around 19,000 lines, and consists of 5 columns. My code is absolutely correct, there are no run time errors nor exceptions. Though, the problem is that when I try to print out data[15000][0], it says null. but my line does have 15,000 lines and it should print out the element inside the array. But when I print out data[5000][0], it works. What could possibly be wrong? I have 19,000 cities in 19,000 different lines, but it seems like when It goes around 10,000+ nothing gets stored in the 2d array. Help please
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Data1
{
public static void main(String[] args)
{
try{
FileReader file = new FileReader("/Users/admin/Desktop/population.csv");
BufferedReader in = new BufferedReader(file);
String title = in.readLine();
String[][] data = new String[20000][5];
int currentRow = 0;
String current;
int i = 0;
String temp;
while ((temp = in.readLine()) !=null)
{
String[] c = new String[5];
String line = in.readLine().replaceAll("\"", ""); //changing the format of the data input
c = line.split(",");
c[1] = c[1].replace(" ", "");
for (int j = 0; j <data[0].length; j++)
{
current = c[j];
data[i][j] = c[j];
}
i++;
}
System.out.println(data[15000][0]);
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
You're throwing away a line on each loop.
while (in.readLine() != null)
should be
String temp;
while ((temp = in.readLine()) != null)
And then no calls to .readLine() inside the loop but refer to "temp".
Read line only once...
String line=null;
while ((line=in.readLine()) !=null) // reading line once here
{
String[] c = new String[5];
line = line.replaceAll("\"", ""); //
c = line.split(",");
c[1] = c[1].replace(" ", "");
One of your errors are the loops
while (in.readLine() !=null)
{
String[] c = new String[5];
String line = in.readLine().replaceAll("\"", ""); //changing the format of the data input
c = line.split(",");
c[1] = c[1].replace(" ", "");
Each time you invoke in.readLine() it reads a line,so you are skipping one line each time since you are calling readline twice(thus reading two lines) but storing only the second line.
You should replace it with.
String line=in.readLine();
while (line !=null)
{
String[] c = new String[5];
line.replaceAll("\"", ""); //changing the format of the data input
c = line.split(",");
c[1] = c[1].replace(" ", "");
//whatever code you have
//last line of the loop
line=in.readLine();
Can you provide us with a couple of lines of your file? And are you sure that all the file is formatted correctly ?

Getting null pointer exception while inserting into two dimensional array of Strings

I have file named input1.txt with contents as below:
a b c d
b d
c d
d e
I want to read it and put them in 2-dimensional array of Strings. I have written code for it. But it is showing NULL POINTER EXCEPTION. Where may be the error? Below is my code:
I am getting the exception in line graphNodes[i][j] = s;
BufferedReader br = null;
BufferedReader cr = null;
int lines = 0;
try {
br = new BufferedReader(new FileReader(filename));
try {
while (br.readLine() != null) {
lines++;
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
List<String> nodes = new ArrayList<String>();
String[][] graphNodes = new String[lines][];
String[] line = new String[lines];
int i = 0;
int j = 0, x = 0;
try {
cr = new BufferedReader(new FileReader(filename));
while (cr.readLine() != null) {
line[x] = cr.readLine();
System.out.println("Line is: " + line[x]);
String[] letters = line[x].split(" ");
for (String s : letters) {
System.out.println("Letter is " + s);
graphNodes[i][j] = s;
j++;
}
i++;
x++;
}
} catch (IOException e) {
e.printStackTrace();
}
the graphNodes is missing column length
String[][] graphNodes = new String[lines][];
in your problem, once you get letters, you can initialize column of 2d array
String[] letters = line[x].split(" ");
graphNodes[i] = new String[letters.length];
You need to instantiate graphNodes[i] before accessing its j index.
I believe you're having issues with the following bit of code:
try {
cr = new BufferedReader(new FileReader(filename));
while (cr.readLine() != null) {
line[x] = cr.readLine();
System.out.println("Line is: " + line[x]);
String[] letters = line[x].split(" ");
for (String s : letters) {
System.out.println("Letter is " + s);
graphNodes[i][j] = s;
j++;
}
i++;
x++;
}
}
This while statement says "while cr.readLine() != null" and at that very moment it read the first line of the file, compared it with null, and it wasn't null so it enters the loop. You then told it to set line[x] equal to cr.readLine() which it then reads the next line of the file, and sets it equal to line[x]. Thus skipping the first line of code doing nothing more with it than using it to check the while loop condition.
I think what you want in your while loop is something like this
try {
cr = new BufferedReader(new FileReader(filename));
for(String lineValue = cr.readLine(); lineValue != null; x++, lineValue = cr.readLine()) {
line[x] = lineValue;
System.out.println("Line is: " + line[x]);
String[] letters = line[x].split(" ");
for (String s : letters) {
System.out.println("Letter is " + s);
graphNodes[i][j] = s;
j++;
}
i++;
}
}
But as someone mentioned previously, You need to declare the size of your 2 dimensional array. For the sake of this loop I just made it String[lines][100] but you'll want to adjust that to meet your needs (however long you anticipate your longest line of letters to be.
Well for one, you are not specifying a value for the second dimension: String[][] graphnodes = new String[lines][].
This means you are basically trying to set s to a value that cannot exist.
you might try defining String[] letters first then doing something like String[][] graphnodes = new String[lines][letters.getLength()];
also,
while (cr.readLine() != null) should be while (cr.hasNextLine())
your code would also look a lot cleaner if you did something like:
for (int i = 0, j = 0, x = 0; cr.hasNextLine(); i++, x++) {
line[x] = cr.readLine();
System.out.println("Line is: " + line[x]);
String[] letters = line[x].split(" ");
for (String s : letters) {
System.out.println("Letter is " + s);
graphNodes[i][j] = s;
j++;
}
}
First of All you don't need to read the files twice. Once to get the number of lines and the other to get the actual data.
You need to read the lines and put them directly in a List. Then you can do whatever you need with that list.

Categories