Array index out of bound in java error - java

package com.testing;
import java.io.BufferedReader;
import java.io.FileReader;
public class CsvParser {
public static void main(String[] args) {
String csvFile = "D:/code-home/SentimentAnalysis/test_data/Sentiment Analysis Dataset.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = "\t"; // data is in format splitted by tab
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] tweet = line.split(cvsSplitBy);
System.out.println(tweet[1]);
System.out.println(tweet[3]);
}
}
}
The program's purpose is to parse the CSV format. I have used bufferRead method.
When I go to compile the program, it works fine. When I run the program,output is printed but there is a exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at com.testing.CsvParser.main(CsvParser.java:34)

First of all: Arrays in Java are Zero-indexed, which means that the first element in an array is not selected by array[1] but by array[0]. Since your OutOufBoundsException is fired at the index 1, your array has at most one element in it (you shoulds check for the size of the array before accessing it). Because you are trying to access the index 3 (fourth element in Java) in the very next line i suspect you expect at least 3 elements in each line. Since there is at most one element you seem to either be using the wrong splitcharacter or your file is not formatted as you expect it to be. I hope this helps you. Kind regards

Related

RDF/XML for apache jena format using java

The error I get when I change list1[0] to list1[1]:
I am doing a progam that prints from a file using RDF model in java, I wanted to let the object to be as a Sting but i couldn’t find a way for it, I tried to make by using the 2-d array to let it reads from the file and print the data into the output screen. However, it doesn't work and I couldn't figure out the reason.
Here is my code:
String synonyms =null;
try {
File file1 = new File("Data/9687.txt");
FileReader fileReader1 = new FileReader(file1);
BufferedReader bufferedReader1 = new BufferedReader(fileReader1);
StringBuffer stringBuffer = new StringBuffer();
String line1;
System.out.println("Proteins & Synonyms:");
while ((bufferedReader1.readLine()) != null) {
line1 = bufferedReader1.readLine();
String[] list1 = line1.split(“/t”)
synonyms=model1.expandPrefix(list1[0]);
proteinG.addProperty(hasSynonyms,synonyms);
And here is the OUTPUT message shown:
<https://Bio2cv.net/ENSP000003488> <hasSynonyms> "ENSP000003488” .
The output for the resource is the same as the string.
Is the synonym name in the second column of the input file?
If so, you are using bad index 0 here:
synonyms=model1.expandPrefix(list1[0]);
Change it to 1 and also remove the model1.expandPrefix() call if you want a plain string literal:
synonyms=list1[1];
For skipping invalid lines (without tab character) change the code after the split() call. Check the length of the list1 array:
String[] list1 = line1.split("\t");
if (list1.length < 2) continue;
You are also reading two lines form the input instead of one.
Change this code:
while ((bufferedReader1.readLine()) != null) {
line1 = bufferedReader1.readLine();
to this:
while ((line1 = bufferedReader1.readLine()) != null) {

Read CSV and convert string to double

I am new to Java and I am reading a csv file using open CSV and my code is below:
import java.io.FileReader;
import java.util.Arrays;
import au.com.bytecode.opencsv.CSVReader;
public class ParseCSVLineByLine
{
double arr []=new arr[10];
public static void main(String[] args) throws Exception
{
//Build reader instance
//Read data.csv
//Default seperator is comma
//Default quote character is double quote
//Start reading from line number 2 (line numbers start from zero)
CSVReader reader = new CSVReader(new FileReader("data.csv"), ',' , '"' , 1);
//Read CSV line by line and use the string array as you want
String[] nextLine;
int i=0;
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null && i<10) {
//Verifying the read data here
arr[i]=Double.parseDouble(Arrays.toString(nextLine).toString());
System.out.println(arr[i]);
}
i++;
}
}
}
But this does not works.But when I only print
Arrays.toString(nextLine).toString()
This prints
[1]
[2]
[3]
.
.
.
.
[10]
I think the conversion is having the problem.Any help is appreciated.
Thing is:
"[1]"
is not a string that could be parsed as number!
Your problem is that you turn the array as a whole into one string.
So instead of calling
Arrays.toString(nextLine).toString()
iterate nextLine and give each array member to parseDouble()!
Besides: I am pretty sure you receive a NumberFormatException or something alike. The JVM already tells you that you are trying to convert an invalid string into a number. You have to learn to read those exception messages and understand what they mean!
Long story short: your code probably wants to parse "[1]", but you should have it parse "1" instead!

My Java program doesn't iterate through my entire CSV file

Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class dataReader {
#SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception {
String splitBy =",";
BufferedReader br = new BufferedReader(new FileReader("C:/practice/testData.csv"));
String line = br.readLine();
int counter = 0;
while ((line = br.readLine()) != null){
counter++;
String[] b = line.split(splitBy);
for (int x = 0; x < b.length; x++){
System.out.println(b[x]);
}
}
System.out.println(counter);
br.close();
}
}
When I run it, it goes through the CSV and displays some output but it starts with product ID 4000+. It basically only outputs results for the last thousand rows in the CSV. I'm wrangling with a really ugly CSV file to try to get some useful data out of it so that I can write all of it into a new database later on. I'd appreciate any tips.
As in the comments, the issue is that System.out.println prints to your console. The console will have a limit to the number of lines it can display, which is why you see the last ~1000 lines.
At a frist glance at your code, you skip the first line by assigning a readline() to your string line
String line = br.readLine();
You should change that as you read the first line and than enter the loop which will read the 2nd line before any operations on the first line took place.
Try something like
String line = "";
Your code won't handle more complicated CSVs, eg a row:
"Robert, John", 25, "Chicago, IL"
is not going to get parsed correctly. Just splitting on ',' is going to separate "Robert, John" into multiple cells though it should be just 1 cell.
The point is, you shouldn't be writing a CSV parser. I highly recommend go downloading the Apache Commons CSV library and using that! Reading CSVs is a solved problem; why reinvent the wheel?
Without seeing the structure of the file I can only speculate, but this line: String line = br.readLine(); needs to be changed to String line = "" or String line = null. As it currently stands, you are discarding your first line.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 (Am I saving my file wrong in Java)?

I am trying to save a file line by line of a file in the form of:
number -> number
number -> number
number -> number
number -> number
etc. etc.
I have saved the file as the following (in Netbeans)
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\jon\\Desktop\\data.txt"));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null){
lines.add(str);
}
String[] graph = lines.toArray(new String[lines.size()]);
I get this error when I run my function (code is syntax past storing the file line by line):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
-1
at different places along my function. I'm assuming this is a problem because I am storing my file, wrong? Why?
So you just want to read in line by line?
I'd use a file and a scanner, also for the array using an arraylist might be easier.
imports you will have to use
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
also use throws IOException
File fileData = new File("C:\\Users\\jon\\Desktop\\data.txt");
ArrayList<String> readFile = new ArrayList();
if (f.exists() && f.isFile() ) {
Scanner sc = new Scanner(fileData);
while (sc.hasNext()) {
String line = sc.next();
readFile.add(line);
}
sc.close();
}
This should work if you want to read in the file, but you mentioned reading them in as numbers, to do this we must use an arraylist of Integers and we need to parse the read in line to Integers, this can be simply done by replacing ArrayList<String> readFile = new ArrayList();
with ArrayList<Integer> readFile = new ArrayList();
AND readFile.add(line); with readFile.add(Integer.parseInt(line));
I hope this will help you out.

Error in regards to 'ArrayIndexOutOfBoundsException' and more?

I cant seem to figure out what is causing this following error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Bank.main(Bank.java:42) <--- this line is referring to the code line that starts as "banklist.add(new Bank(values[0]...."
public static void main (String[] args) throws FileNotFoundException
{
FileReader fr = new FileReader("Bank Data.txt");
BufferedReader reader = new BufferedReader(fr);
List<Bank> banklist = new ArrayList<Bank>();
try {
String line;
while ((line = reader.readLine()) != null)
{
String[] values = line.split("/t"); // Split on "tab"
banklist.add(new Bank(values[0], Integer.parseInt(values[1]),Integer.parseInt(values[2]),Integer.parseInt(values[3]),Integer.parseInt(values[4]), values[5])); // Create a new Player object with the values extract and add it to the list
Most possible explanation is that in your file, there are lines which does not have tab. Maybe last line is empty.
Possible solution may be to do a defensive programming and check the length of array before directly indexing it as array[1].
You have split on /t rather than \t. Note backslash rather than forward slash.
Since your lines probably don't contain any /t sequences, you don't get all the words your code expects.
You have used Wrong expression.
Find below Solution..
while ((line = reader.readLine()) != null) {
String regexp = "[\\s,;\\t]+";
String[] values = line.split(regexp);
banklist.add(new Bank(values[0],
Integer.parseInt(values[1]),
values[2],
values[3],
Integer.parseInt(values[4]),
values[5])
);
}

Categories

Resources