java.lang.ArrayIndexOutOfBoundsException how to remove this error? - java

how do I get rid of the ArrayIndexOutOfBoundsException?
Here is the code that triggers the exception:
FileReader fr;
try {
System.out.println(4);
fr = new FileReader("SOME FILE PATH");
BufferedReader br = new BufferedReader(fr);
String in ;
while (( in = br.readLine()) != null) {
String[] lines = br.readLine().split("\n");
String a1 = lines[0];
String a2 = lines[1];
System.out.println(a2 + " dsadhello");
a11 = a1;
String[] arr = a11.split(" ");
br.close();
System.out.println(arr[0]);
if (arr[0].equals("echo")) {
String s = a11;
s = s.substring(s.indexOf("(") + 1);
s = s.substring(0, s.indexOf(")"));
System.out.println(s);
save++;
System.out.println(save + " save numb");
}
}
System.out.println(3);
} catch (FileNotFoundException ex) {
System.out.println("ERROR: " + ex);
} catch (IOException ex) {
Logger.getLogger(game.class.getName()).log(Level.SEVERE, null, ex);
}
and heres the file I'm pulling from:
echo I like sandwiches (hello thee it work)
apples smell good
I like pie
yes i do
vearry much

Exception is likely to be generated from the below line:
String a2 = lines[1];
We are using br.readLine() to read from file. This method reads only one line and returns it as a String. As it is only one line, it won't have '\n' and hence, splitting it with '\n' will result in an array with only one element (i.e. 0).
To make it work, we need to replace the below lines:
String[] lines = br.readLine().split("\n");
String a1 = lines[0];
String a2 = lines[1];
System.out.println(a2 + " dsadhello");
with
String a1 = in;
We don't need a2 here and we are already reading the line in while loop. There is no need to read it again.

In this part
String in;
while ((in = br.readLine()) != null) {
String[] lines = br.readLine().split("\n");
String a1 = lines[0];
String a2 = lines[1];
System.out.println(a2 + " dsadhello");
a11 = a1;
you read a line and ignore it, then read another line and tried splitting it by "\n". Unfortunately, there will be not \n in what is returned by br.readLine(), therefore lines will have only one elment and acceccing line[1] become illegal.
Intead of this, you can simply write
while ((all = br.readLine()) != null) {

Related

Java read specific parts of a CSV

I created the following code to read a CSV-file:
public void read(String csvFile) {
try {
File file = new File(csvFile);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
String[] tempArr;
while((line = br.readLine()) != null) {
tempArr = line.split(ABSTAND);
anzahl++;
for(String tempStr : tempArr) {
System.out.print(tempStr + " ");
}
System.out.println();
}
br.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
I have a CSV with more than 300'000 lines that look like that:
{9149F314-862B-4DBC-B291-05A083658D69};Gebaeude;TLM_GEBAEUDE;;Schiessstand;{41C949A2-9F7B-41EE-93FD-631B76F2176D};Altdorf 300m;offiziell;Hochdeutsch inkl. Lokalsprachen;Einfacher Name;;684600;295930;400
How can I now only get the some parts out of that? I only need the bold/italic parts to work with.
Without further specifying what your requirements/input limitations are the following should work within your loop.
String str = "{9149F314-862B-4DBC-B291-05A083658D69};Gebaeude;TLM_GEBAEUDE;;Schiessstand;{41C949A2-9F7B-41EE-93FD-631B76F2176D};Altdorf 300m;offiziell;Hochdeutsch inkl. Lokalsprachen;Einfacher Name;;684600;295930;400";
String[] arr = str.split("[; ]", -1);
int cnt=0;
// for (String a : arr)
// System.out.println(cnt++ + ": " + a);
System.out.println(arr[6] + ", " + arr[15] + ", " + arr[16]);
Note that this assumes your delimiters are either a semicolon or a space and that the fields desired are in the fix positions (6, 15, 16).
Result:
Altdorf, 684600, 295930

Assigning a value of a String to a String Array

I doing some coding related to my project. I need to assign simply a string value to a String array reading from a file.
But I can't understand why the value keeps always null. The values of string doesn't assign to the array. Can someone explains me the mistake I have done.
Here I have posted my code.
Test.java
public class Test {
public static void main(String[] args) throws IOException {
//Tuning Jaccard Coefficient algorithm for Training set
ReadFile_2 rf = new ReadFile_2();
rf.readFile("C:/Users/user/Desktop/Msc-2016/InformationRetrieval/project material/train.txt","Training");
}
}
ReadFile_2.java
class ReadFile_2 {
List<String> copying_strings1 = new ArrayList<>();
String[] Apparted_Strings = new String[3];
String[] copying_strings = new String[50];
int arryListSize = copying_strings.length;
static int value_of_shingle;
static int best_Shingle;
String[] fileType;
int fileType_size;
public void readFile(String fileName, String file_type) throws FileNotFoundException, IOException {
//Name of the file
try {
if (file_type.equals("Training")) {
best_Shingle = 2;
} else if (file_type.equals("Testing")) {
best_Shingle = value_of_shingle;
}
FileReader inputFile = new FileReader(fileName);
BufferedReader bufferReader = new BufferedReader(inputFile);
String line;
int r = 0;
while ((line = bufferReader.readLine()) != null) {
copying_strings[r] = line;
r++;
System.out.println("lll " + copying_strings[r]);
System.out.println("lll " +line);
//Apparted_Strings = sp.apart_Strings_3(line);
//CallingAlgo_4 c_a = new CallingAlgo_4(Apparted_Strings[0], Apparted_Strings[1], Apparted_Strings[2], best_Shingle, "Jaccard");
}
//Close the buffer reader
bufferReader.close();
} catch (Exception e) {
System.out.println("Error while reading file line by line:" + e.getMessage());
}
}
}
Can someone please let me know why the value of
System.out.println("lll " + copying_strings[r]);
prints always as null.
You increment the while loop variable (r) before printing the string value.
So it prints the next array value that is null.
So please increment the variable (r) after printing the string value as mentioned below,
while ((line = bufferReader.readLine()) != null) {
copying_strings[r] = line;
System.out.println("lll " + copying_strings[r++]);
System.out.println("lll " +line);
}
You have a mistake in your while-loop. The correct sequence is to read a line first, pass it to String, print it and finally increment the looped variable.
while ((line = bufferReader.readLine()) != null) { // read a line
copying_strings[r] = line; // pass to String
System.out.println("lll " + copying_strings[r]); // print for the 1st time
System.out.println("lll " + line); // print for the 2nd time
r++; // increment the looped variable
}
If you print the variable copying_strings after incrementing r++, you get obviously null because nothing has been passed in it.

Print specific lines(Words/numbers) from csv file

Lets say I have CSV file like this:
Football Contest blabla bla,,,,,,,
Team number1,Team number2,Points team1,Points team2,Red cards
Sweden,France,1,2,"
Sweden,Brazil,3,5,2
Sweden,Germany,2,2,3
Sweden,Spain,3,5,"
And in this file I only want to print out the matches that got red cards. So in this example I would like to print:
Sweden - Brazil = 2 Sweden - Germany = 3
This is my current code, and Im stuck how to move on.
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String lines = br.readLine();
String result[] = lines.split(",");
do{
System.out.println();
}while((lines = br.readLine()) != null);
//String result[] = lines.split(",");
//System.out.println(result[1]);
br.close();
}catch (FileNotFoundException e){
System.out.println("File not found : "+ file.toString());
}catch (IOException e ){
System.out.println("Unable to read file: "+ file.toString());
}
EDIT I got helped with:
while (line != null) {
String result[] = line.split(",");
if (result.length == 5) { //red cards present?
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
line = br.readLine(); //read next
}
But the problem I have now is that it still prints all because of the " in the csv file. Why cant I do something like this?
if (result[4] == "1,2,3,4,5" ){
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
If you the index of red card and it looks like Integer, Then see for that index is integer or not if Yes the print 0,1 and 4
index[0]=Team number1
index[1]=Team number2
index[4]=red cards
Your try-catch block should look like this:
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
String result[] = line.split(",");
if (result.length == 5 && result[4].matches("[0-9]")) { //red cards present?
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
line = br.readLine(); //read next
}
//close readers
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("File not found : " + file.toString());
} catch (IOException e) {
System.out.println("Unable to read file: " + file.toString());
}
If there are trailing whitespaces in your file, you have to trim the String first: result[4].trim().matches("[0-9]") or use another regex: result[4].matches("\\d\\s")
Why cant I do something like this?
if (result[4] == "1,2,3,4,5" ){
The problem with this is == tests for identity: it will compare if the reference in result[4] is the same reference as the constant in your source code. That expression will always be false. You need to check for equality, not identity:
if (Objects.equals(result[4], "1,2,3,4,5")) {
or
if (result[4] != null && result[4].equals("1,2,3,4,5")) {
or
if ("1,2,3,4,5".equals(result[4])) {
Note that Objects.equals() was (finally) added to the Java standard library in Java 8. Without it, you must guard against a NullPointerException before you call the .equals() method on an object. Traditionally I have preferred the last version because invoking the method on the string literal means I can be assured it is never null and will just work.
You can try like this
public class HelloWorld{
public static void main(String []args){
String str1= "Sweden,Brazil,3,5,4";
String str2="Sweden,Germany,2,2,3";
String str3="Football Contest blabla bla,,,,,,,";
String result1[]=str1.split(",");
String result2[]=str2.split(",");
String result3[]=str3.split(",");
if(result1.length>=5){
System.out.print(result1[0]+"-"+result1[1]+"="+result1[4]);
System.out.println();
}
if(result2.length>=5){
System.out.print(result2[0]+"-"+result2[1]+"="+result2[4]);
System.out.println();
}
if(result3.length>=5){
System.out.print(result3[0]+"-"+result3[1]+"="+result3[4]);
System.out.println();
}
}
}
try this:
do {
if (result[4] instanceof Integer) {
System.out.print(result[0]+"="+result[1]+"="+result[4])
}
} while ((lines = br.readLine()) != null);

split a string twice, but the second time i got an error

I need to split a string twice in order to apply a metric on an OWL file. first time it's ok,and the array parts get two elements,but the second time the array firstDataSet is empty and i got this error : Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: 1. any help please?
String line;
String[] parts = new String [4];
String[] firstDataSet = new String [4];
String[] secondDataSet = new String [4];
double externalSameAsCounter = 0;
double externalEdgeCounter = 0;
double ratio = 0;
try{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
line = br.readLine();
while ((line = br.readLine())!= null ){
if(line.contains("->") && line.contains(".")){
parts = line.split("->");
firstDataSet = parts[0].split(".");
if(parts[1].contains("http")){
secondDataSet = parts[1].split(".");
}
if(((firstDataSet[1].toLowerCase()).contains(secondDataSet[1].toLowerCase()))){
externalEdgeCounter = externalEdgeCounter + 1;
}
}
if(line.contains("owl:sameAs")){
parts = line.split("->");
firstDataSet = parts[0].split(".");
secondDataSet = parts[1].split(".");
if(!((firstDataSet[1].toLowerCase()).contains(secondDataSet[1].toLowerCase()))){
externalSameAsCounter = externalSameAsCounter +1;
}
}
}
}
catch (FileNotFoundException ex){
System.out.println(
"Unable to open file");
}
catch(IOException ex) {
System.out.println(
"Error reading file");
}
ratio = (double)(externalSameAsCounter / externalEdgeCounter);
return ratio;
In the second if block, you're splitting on "->", but you have no guarantee the string contains that substring, because all you checked was whether the string contained "owl:sameAs".
When regular expressions, . means any character and if you split on . it will not do what you expect. I suggest trying "[.]" which means . literally.

java regular expression getting values from a txt file [duplicate]

I am new to Java. I have one text file with below content.
`trace` -
structure(
list(
"a" = structure(c(0.748701,0.243802,0.227221,0.752231,0.261118,0.263976,1.19737,0.22047,0.222584,0.835411)),
"b" = structure(c(1.4019,0.486955,-0.127144,0.642778,0.379787,-0.105249,1.0063,0.613083,-0.165703,0.695775))
)
)
Now what I want is, I need to get "a" and "b" as two different array list.
You need to read the file line by line. It is done with a BufferedReader like this :
try {
FileInputStream fstream = new FileInputStream("input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int lineNumber = 0;
double [] a = null;
double [] b = null;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
lineNumber++;
if( lineNumber == 4 ){
a = getDoubleArray(strLine);
}else if( lineNumber == 5 ){
b = getDoubleArray(strLine);
}
}
// Close the input stream
in.close();
//print the contents of a
for(int i = 0; i < a.length; i++){
System.out.println("a["+i+"] = "+a[i]);
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Assuming your "a" and"b" are on the fourth and fifth line of the file, you need to call a method when these lines are met that will return an array of double :
private static double[] getDoubleArray(String strLine) {
double[] a;
String[] split = strLine.split("[,)]"); //split the line at the ',' and ')' characters
a = new double[split.length-1];
for(int i = 0; i < a.length; i++){
a[i] = Double.parseDouble(split[i+1]); //get the double value of the String
}
return a;
}
Hope this helps. I would still highly recommend reading the Java I/O and String tutorials.
You can play with split. First find the line in the text that matches "a" (or "b"). Then do something like this:
Array[] first= line.split("("); //first[2] will contain the values
Then:
Array[] arrayList = first[2].split(",");
You will have the numbers in arrayList[]. Be carefull with the final brackets )), because they have a "," right after. But that is code depuration and it is your mission. I gave you the idea.

Categories

Resources