This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 8 months ago.
I have the following service for to get values inside a string document, this service is called inside a for, getting the data for every flight and then generate a PDF.
I'm getting the Index 2 out of bounds for length 1 when try to call the service, this is the code:
private Map<String, Object> readFileLsd(String content) {
Map<String, Object> mapResult = new LinkedHashMap<>();
try {
Reader inputString = new StringReader(content);
BufferedReader br = new BufferedReader(inputString);
String line;
String TotalBaggagesCargo = "";
String PASSENGER = "";
String TOTAL_TRAFFIC = "";
String validCharacters = "[\\x00-\\x1F]|[\\x21-\\x2c]|[\\x3B-\\x40]|[\\x5B-\\x60]|[\\x7B-\\xFF]";
while ((line = br.readLine()) != null) {
line = line.replaceAll(validCharacters, "").trim();
if (line.startsWith("LOAD IN COMPARTMENTS")) {
TotalBaggagesCargo = line;
}
if (line.startsWith("PASSENGER/CABIN BAG")) {
PASSENGER = line;
}
if (line.startsWith("TOTAL TRAFFIC LOAD")) {
TOTAL_TRAFFIC = line;
}
}
mapResult.put("TotalBaggagesCargo", TotalBaggagesCargo.trim().replaceAll("\\s+", " ").split(" ")[3]);
mapResult.put("PASSENGER", PASSENGER.trim().replaceAll("\\s+", " ").split(" ")[2]);
mapResult.put("TOTAL_TRAFFIC", TOTAL_TRAFFIC.trim().replaceAll("\\s+", " ").split(" ")[3]);
} catch (Exception e) {
e.printStackTrace();
}
return mapResult;
}
Underlying Problem
The line which starts with PASSENGER/CABIN BAG apparently has only one whitespace character and when you split it by a space it results in a String array with only one entry.
Possible solution
If the amount of passengers is sometimes not present in the input String, then you could make the put of key conditional.
String[] passengers = PASSENGER.trim().replaceAll("\\s+", " ").split(" ");
if (passenger.length > 2) mapResult.put("PASSENGER", passengers[2]);
This might bring different problems later in your program. So before working around it, you must try to understand, why it is absent. If it is reasonable that it is missing, then the workaround is acceptable, maybe you will need an else-case like that
else mapResult.put("PASSENGER", "");
when the key has to be present later on.
Related
This question already has answers here:
ArrayIndexOutOfBoundsException for String.split()
(2 answers)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I got ArrayIndexOutOfBoundsException: 1 at this line String name = pieces[1]; in the following function:
public static void loadFile() throws FileNotFoundException, IOException {
file = new File("C:\\Users\\DELL\\OneDrive - Philadelphia University\\Desktop\\NetBeansProjects\\CaloriesIntakeApp\\src\\main\\webapp\\WEB-INF\\data\\data.txt");
try (BufferedReader inputStream = new BufferedReader(new FileReader(file))) {
String line;
while ((line = inputStream.readLine()) != null) {
String[] pieces = line.split(" ");
String id = pieces[0];
String name = pieces[1];
int grms = Integer.parseInt(pieces[2]);
int calories = Integer.parseInt(pieces[3]);
String photo = pieces[4];
Fruit f = new Fruit(id, name, grms, calories, photo);
fruitList.add(f);
}
}
}
Need to know the reason!
Check if your data is clean in the file (data.txt). It will not work if there is a single empty line or basically any line not in the desired format.
Example:
a12387beac8 Apple 1 1500 /location/photo.jpeg
I hope you are trying to split based on white space.
try this:
String[] pieces = line.split("\\s+");
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I'm working on a text based game to run out of the Command Prompt that simulates Decking in Shadowrun. Ideally, the player should be able to have a CSV file (65 rows, 2 columns) with all the character's pertinent information, and that information should be able to be uploaded into the program.
I am at the point where the csv file is properly loaded and displays everything correctly, while still in the loop. I cannot for the life of me figure out how to get the values out of the loop and into something that I can use to set the values of the various character stats. Snippets of my code are as follows:
public class Program {
static int[][] Character = new int[65][2];
public static void main (String[]args) {
Scanner user_input = new Scanner(System.in);
String DeckerName;
System.out.println("What is your name? (Name of your .csv file)"); //Load Decker character
DeckerName = user_input.nextLine();
System.out.println("Alright, " + DeckerName + ". Jacking into the Matrix now...");
String csvFile = "FILE LOCATION";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
Scanner loader = new Scanner(System.in);
//Opens and loads .csv file into an array
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String characterload[] = line.split(cvsSplitBy);
System.out.println ("" + characterload[0] + ": " + characterload[1]); // for testing purposes, characterload[0] is a text description, characterload[1] is an integer
int intDeckerProgram = Integer.parseInt(characterload[1]);
System.out.println(intDeckerProgram); //for testing purposes
for (int i = 0; i < characterload.length; i++)
{
Character[i][1] = intDeckerProgram;
System.out.println(Character[i][1]); //for testing purposes
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br!= null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
int DeckerDetectionFactor = Character[0][1];
System.out.println(Character[0][1]); //for testing purposes
System.out.println(DeckerDetectionFactor); //for testing purposes
int DeckerHackingPool = Character[1][1];
System.out.println(Character[1][1]); //for testing purposes
System.out.println(DeckerHackingPool); //for testing purposes
TL;DR without downloading other java packages, how can I bring the values imported into the characterload array, and put them into the Character array so that my integers are properly initialized? Thank you for your time, I truly appreciate it!
Edit: The two values at the bottom, DeckerDetectionFactor and DeckerHackingPool, need to be 6 and 9, respectively (this info being drawn from the CSV file). I am looking for a little direction on how to ensure these values are properly loaded into the Character[][] array so the variables are initialized properly instead of being put at 0.
After some helpful advice as given, I ended up removing the inner For loop from the While loop. Setting up a row integer followed by incrementing that solved the whole issue. If it helps anyone, here is the code I am using now:
...
br = new BufferedReader(new FileReader(csvFile));
int row = 0;
while ((line = br.readLine()) != null) {
String characterload[] = line.split(cvsSplitBy);
int intDeckerProgram = Integer.parseInt(characterload[1]);
Character[row][1] = intDeckerProgram;
row++;
}
...
I am trying to iterate through a CSV file in Java. It iterates through the entire file, but will get to the end of the file and try to read the next blank line and throw an error. My code is below.
public class Loop() {
public static void main(String[] args) {
BufferedReader br = null;
String line = "";
try {
HashMap<Integer, Integer> changeData = new HashMap<Integer, Integer>();
br = new BufferedReader(new FileReader("C:\\xxxxx\\xxxxx\\xxxxx\\the_file.csv"));
String headerLine = br.readLine();
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
/*Below is my latest attempt at fixing this,*/
/*but I've tried other things too.*/
if (data[0].equals("")) { break; }
System.out.println(data[0] + " - " + data[6]);
int changeId = Integer.parseInt(data[0]);
int changeCv = Integer.parseInt(data[6]);
changeData.put(changeId, changeCv);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Like I typed, this works fine until it gets to the end of the file. When it gets to the end of the file, I get the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at com.ucg.layout.ShelfTableUpdates.main(ShelfTableUpdates.java:23). I've stepped through the code by debugging it in Spring Tool Suite. The error comes up whenever I try to reference data[0] or data[6]; likely because there is nothing in that line. Which leads me back to my original question of why it is even trying to read the line in the first place.
It was my understanding that while ((line = br.readLine()) != null) would detect the end of the file, but it doesn't seem to be. I've tried re-opening the file and deleting all of the blank rows, but that did not work.
Any idea how I can detect the end of the file so I don't get an error in this code?
ANSWER:
Credit goes to user #quemeraisc. I also was able to replace the commas with blanks, and if the line then equals null or "", then you know that it is the end of the file; in my case, there are no blank rows before the end of the file. This still does not solve the problem of detecting the end of the file in that if I did have blank rows in between my data that were not the EOF then this would detect those.
Solution 1:
if (data.length < 7) {
System.out.println(data.length);
break;
}
Solution 1:
if (line.replace(",", "").equals(null) || line.replace(",", "").equals("")) {
System.out.println(line.replace(",", ""));
break;
}
Just skip all blank lines:
while ((line = br.readLine()) != null) {
if( line.trim().isEmpty() ) {
continue;
}
....
....
The last line may contain some control characters (like new line, carriage return, EOF and others unvisible chars), in this case a simple String#trim() doesn't remove them, see this answer to know how to remove them: How can i remove all control characters from a java string?
public String readLine() will read a line from your file, even empty lines. Thus, when you split your line, as in String[] data = line.split(","); you get an array of size 1.
Why not try :
if (data.length >= 7)
{
System.out.println(data[0] + " - " + data[6]);
int changeId = Integer.parseInt(data[0]);
int changeCv = Integer.parseInt(data[6]);
changeData.put(changeId, changeCv);
}
which will make sure there are at least 7 elements in your array before proceeding.
To skip blank lines you could try:
while ((line = reader.readLine()) != null) {
if(line.length() > 0) {
String[] data = line.split(",");
/*Below is my latest attempt at fixing this,*/
/*but I've tried other things too.*/
if (data[0] == null || data[0].equals("")) { break; }
System.out.println(data[0] + " - " + data[6]);
int changeId = Integer.parseInt(data[0]);
int changeCv = Integer.parseInt(data[6]);
changeData.put(changeId, changeCv);
}
}
Instead of replace method use replaceAll method. Then it will work.
I have a textfile as such:
type = "Movie"
year = 2014
Producer = "John"
title = "The Movie"
type = "Magazine"
year = 2013
Writer = "Alfred"
title = "The Magazine"
What I'm trying to do is, first, search the file for the type, in this case "Movie" or "Magazine".
If it's a Movie, store all the values below it, i.e
Set the movie variable to be 2014, Producer to be "John" etc.
If it's a Magazine type, store all the variables below it as well separately.
What I have so far is this:
public static void Parse(String inPath) {
String value;
try {
Scanner sc = new Scanner(new FileInputStream("resources/input.txt"));
while(sc.hasNextLine()) {
String line = sc.nextLine();
if(line.startsWith("type")) {
value = line.substring(8-line.length()-1);
System.out.println(value);
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(LibrarySearch.class.getName()).log(Level.SEVERE, null, ex);
}
}
However, I'm already having an issue in simply printing out the first type, which is "Movie". My program seems to skip that one, and print out "Magazine" instead.
For this problem solely, is it because the line: line.startsWith("type")is checking if the current line in the file starts with type, but since the actual String called lineis set to the nextline, it skips the first "type"?
Also, what would be the best approach to parsing the actual values (right side of equal sign) below the type "Movie" and "Magazine" respectively?
I recommend you try the following:
BufferedReader reader = new BufferedReader(new FileReader(new File("resources/input.txt")));
String line;
while((line = reader.readLine()) != null) {
if (line.contains("=")) {
String[] bits = line.split("=");
String name = bits[0].trim();
String value = bits[1].trim();
if (name.equals("type")) {
// Make a new object
} else if (name.equals("year")) {
// Store in the current object
}
} else {
// It's a new line, so you should make a new object to store stuff in.
}
}
In your code, the substring looks suspect to me. If you do a split based on the equals sign, then that should be much more resilient.
This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
i have wrote the code to read a 3rd column of a file(treeout1.txt) and write those contents in another file(tree.txt).and now i want to open tree.txt and write the contents to stem.txt,where tree.txt contents a single word in each row and a delimiter is found at the end of each line.i have attached that txt file below.you can view that to have better understanding.now i want to write the words into a line till a delimiter "###" is found...for example 'the girl own paper' and next line vol and so on....i have tried that but ArrayIndexOutOfBoundsException comes for a[]...why?and how to resolve that?
the text file tree.txt is given below
the
girl
own
paper
###
vol
###
viii
###
no
###
#card#
###
October
#card#
#card#
###
price
one
penny
###
as
the
baron
have
conjecture
the
housemaid
whom
he
have
call
out
of
the
nursery
to
look
for
###
lons
cane
on
find
her
master
have
go
without
it
do
not
hurry
back
but
stop
talk
###
Code:
package simple;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Simple {
public static void main(String[] args) throws IOException {
String line;
String line2;
String[] a = new String[100];
int i = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("C:/TreeTagger/treeout1.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("D:/tree.txt"));
String separator = System.getProperty("line.separator");
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, "\n");
while (st2.hasMoreElements()) {
String line1 = (String) st2.nextElement();
String[] array = line1.split("\\s+", 3);
//System.out.println(array[2]);
output.append(array[2]);
output.newLine();
}
}
output.close();
br.close();
BufferedReader br1 = new BufferedReader(new FileReader("D:/tree.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("D:/stem.txt"));
while ((line2 = br1.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line2, " ");
while (st.hasMoreTokens()) {
String element = st.nextToken();
System.out.println(element);
while (element != "###") {
a[i] = element;
i++;
}
out.append(a[i]);
element = element.replace(element, "");
}
}
} catch (IOException e) {
}
}
}
You need to reset i to 0 after you find the ### delimiter. Otherwise you will keep incrementing i until it gets larger than 100 (a's maximum).
Also you can't use the != operator on Strings (from your code: element != "###"). You need to use the following:
!"###".equals(element);