How to fix java.lang.ArrayIndexOutOfBoundsException error - java

I am getting an error when trying to use a JFileChooser to scan a text file add it to an array and parse one of the strings to a double and two to integers. Does it have to do with the fact that the addEmployee method adds the six parameters to an arrayList? Here is the code...
else if (e.getSource()==readButton){
JFileChooser fileChooser = new JFileChooser("src");
if (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
empFile=fileChooser.getSelectedFile();
}
Scanner scan = new Scanner("empFile");
while(scan.hasNext()){
String[] rowData = scan.next().split(":");
if(rowData.length == 5){
rowData[4] = null;
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
}
else{
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
}
if (position2.equals("Manager")){
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else if(position2.equals("Sales")){
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else{
c.addEmployee(fName, lName, position2, firstParam, secondParam, empNum);
}
}
}
John:Smith:Manufacturing:6.75:120:444
Betty:White:Manager:1200.00:111
Stan:Slimy:Sales:10000.00:332
Betty:Boop:Design:12.50:50:244

You are trying to fetch empNum = Integer.parseInt(rowData[5]);
row data only having size 5 that means index 0-4, Thats why ArrayIndexOutOfBoundsException is getting
So Initialize String[] rowData = new String[6];

String[] rowData = new String[5]; // edited out of original post
rowData = scan.next().split(":");
The first statement allocates an array of 5 Strings and sets them all to null. The second statement just throws away the array you just allocated. The result of split will return an array of however many items it finds, and then you assign rowData, which is a reference to an array, to a reference to the new array. The old one gets garbage collected. So there's no guarantee that rowData will have 5 elements after this assignment.
You'll have to decide what you want to do if the split doesn't return enough array elements. You could use something like Arrays.copyOf that could put the split result into some of the rowData elements while leaving the rest alone, but then the unassigned elements will still be null, and you'll just get a NullPointerException a few lines later. So you have some design decisions to make here.
More: You may want to consider using the Scanner method nextLine() instead of next(). next() will return just one token, which means it will stop at a space character, which means you will have problems if someone is named "Mary Beth" or something like that.

Related

Java .split() Array out of bounds

I keep getting this Array out of bounds error for the following code.
brock.txt = reflection program, routine, Arrow, snake game,
public static void main(String[] args) {
String filename = "brock.txt";
String line;
String [] cities = {};
int x = 0;
try {
BufferedReader eshread = new BufferedReader( new FileReader (filename));
line = "";
while ((line = eshread.readLine()) != null ) {
String[] store = line.split(",");
System.out.println(store[0]);
System.out.println(store[1]);
System.out.println(store[2]);
cities[x] = store[2]; //< keep getting an error here
x++;
}//end while loop
eshread.close();
}//end try
catch(IOException iox) {
System.out.println("failiure");
}//end catch
String [] cities = {} will make the array size to 0,when x is greater than 0 the error will occur,that's the reason,so you need to make cities a fixed size at first or use List to do it
You Must define the size of cities or use a list .
You initialized cities with an empty array({}), which means it has a length of 0(not an null, but an empty array). By using cities[0] you are expecting it has at least one element, which is not true.
To fix this, use an ArrayList<String> instead of a String array.
In agreement with the other comments. The issue is with the size of cities array which is being set to 0 and hence the issue for array out of bounds.
I tried the following code and it works if you want to work with a String array.
Else an ArrayList is a better solution if the size is not defined.
String [] cities = new String[10];

java array: split elements

I've got a program that will read from a file and add each line of the file as an element of an array. What I'm trying to do now though is to figure out how to edit certain items in the array.
The problem is my input file looks like this
number of array items
id, artist name, date, location
id, artist name, date, location
so for example
2
34, jon smith, 1990, Seattle
21, jane doe, 1945, Tampa
so if I call artArray[0] I get 34, jon smith, 1990, Seattle but I'm trying to figure out how to just update Seattle when the id of 34 is entered so maybe split each element in the array by comma's? or use a multidimensional array instead?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ArtworkManagement {
/**
* #param args
*/
public static void main(String[] args) {
String arraySize;
try {
String filename = "artwork.txt";
File file = new File(filename);
Scanner sc = new Scanner(file);
// gets the size of the array from the first line of the file, removes white space.
arraySize = sc.nextLine().trim();
int size = Integer.parseInt(arraySize); // converts String to Integer.
Object[] artArray = new Object[size]; // creates an array with the size set from the input file.
System.out.println("first line: " + size);
for (int i = 0; i < artArray.length; i++) {
String line = sc.nextLine().trim();
// line.split(",");
artArray[i] = line;
}
System.out.println(artArray[0]);
sc.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are almost there, but split returns an array, so you need an array of arrays.
You can change this line
Object[] artArray = new Object[size];
By this one, you also can use String instead of Object since this is indeed an string.
String[][] artArray = new Object[size][];
Then you can add the array to the array of arrays with
artArray[i] = line.split();
And finally access to it using two indexes:
artArray[indexOfTheArray][indexOfTheWord]
Also if you want to print the array use:
System.out.println(Arrays.toString(artArray[0]));
This behavior is explicitly documented in String.split(String regex) (emphasis mine):
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
If you want those trailing empty strings included, you need to use String.split(String regex, int limit) with a negative value for the second parameter (limit):
String[] array = values.split(",", -1);
or
String[] array = values.split(",");
so
1. array[0] equals to id
2. array[1] equals to artist name
3. array[2] equals to date
4. array[3] equals to location
String[][] artArray = new String[size][];
System.out.println("first line: " + size);
for (int i = 0; i < artArray.length; i++) {
String line = sc.nextLine().trim();
artArray[i] = new String[line.split(",").length()];
artArray[i]=line.split(",");
}
I think you need to use a better data structure to store the file content so that you can process it easily later. Here's my recommendation:
List<String> headers = new ArrayList<>();
List<List<String>> data = new ArrayList<List<String>>();
List<String> lines = Files.lines(Paths.get(file)).collect(Collectors.toList());
//Store the header row in the headers list.
Arrays.stream(lines.stream().findFirst().get().split(",")).forEach(s -> headers.add(s));
//Store the remaining lines as words separated by comma
lines.stream().skip(1).forEach(s -> data.add(Arrays.asList(s.split(","))));
Now if you want to update the city (last column) in the first line (row), all you have to do is:
data.get(0).set(data.get(0) - 1, "Atlanta"); //Replace Seattle with Atlanta

how to build an string array from a string and integers in java

I have to put in a string array some values resulting from several parsed html pages. So the first value it's a name and all the others are numbers. After I must return the array to main to print. Obviously I make something wrong .
this is part of my newbie code...
String[] ret = null;
int y = 0;
for (Element h1 : h1s) {
// Using Jsoup to scrape the html file and find H1 text
h1_id = h1.className();
// I put here the text of H1
h1_text = h1.text();
if (h1_id.equals("ezomat-logo-text ezCSS")) {
// jump to the next h1
} else {
// I want to put the txt as the first array place
ret[y] = "'" + h1_text + "'";
}
i = 0;
// found the number values single integers with comma
for (Element image : images) {
Imm[i] = "," + imageName;
i++;
}
i = 0;
y = 1;
// y = 1 because I want to start from the second position.
for (Element image : images) {
ret[y] = Imm[i];
i++;
y++;
}
}
return ret;
You can't dynamicly resize an array, you have to initialize it with a fixed size.
So, you have to initialize it with
String[] ret = new String[size];
where size have to be the number of elements you are going to put into your array.
Or the better approach: Use ArrayList<String>instead. Initialize it with
ArrayList<String> ret = new ArrayList<String>();
and add your Items with ret.add("whatever");.
On the first line of your code you attempt to define an array without a size, but you don't actually define it, you just assign null.
Also, it's impossible to dynamically add elements to such array.
For these scenarios we have List.
To define a List that stores Strings use the following code:
List<String> ret = new ArrayList<String> ();
And then proceed to add elements to this array like so:
ret.add ("," + imageName);
To retrieve a value from an index in the list do the following:
ret.get(index);
Java does not allow arrays with variable length. I think that this is your main problem.
There are two choiches:
Obtain the array length first and instantiate the array accordingly
String[] ret = new String[100];
Use an ArrayList
ArrayList<String> ret = new ArrayList<String>();
You can add elements to the ArrayList like this: ret.add(value);
The Java Tutorial: Arrays
java.util.ArrayList reference

How to loop through an array and check for duplicates?

I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;
You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}
It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.
When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.
Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.
To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.
while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}
You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.

How to compare against a null element in an array in java?

I have a program where I need to store the results in an arraylist:-
public class ReseedingDBRandomElements {
public static void main(String[] args){
try {
// getting the field Keyword from the csv
String csvfile="/Users/dray/Downloads/ReseedingDBRandomKeywords.csv";
BufferedReader br =new BufferedReader(new FileReader(csvfile));
StringTokenizer st = null;
String line="";
int linenumber=0;
int columnnumber;
// initializing the parameter for each column
int free = 0;
int free1 = 0;
// create the ArrayList
ArrayList<String> Keyword = new ArrayList<String>();
ArrayList<String> Alternate = new ArrayList<String>();
// reading through the csv file
while((line=br.readLine())!=null){
linenumber++;
columnnumber = 0;
st = new StringTokenizer(line,",");
while(st.hasMoreTokens()){
columnnumber++;
String token = st.nextToken();
if("Keyword".equals(token)){
free=columnnumber;
System.out.println("The value of free :"+free);
}else if ("Alternate".equals(token)){
free1=columnnumber;
System.out.println("The value of free1 :"+free1);
}
if(linenumber>1){
if (columnnumber==free)
{
Keyword.add(token);
}else if (columnnumber==free1){
Alternate.add(token);
}
}
}
}
// converting the keyword ArrayList to an array
String[] keyword = Keyword.toArray(new String[Keyword.size()]);
for(int i=0;i<keyword.length;i++){
System.out.println(" The value of the keyword is :"+keyword[i]);
}
// converting the alternate ArrayList to an array
String[] alternate = Alternate.toArray(new String[Alternate.size()]);
for(int i=0;i<alternate.length;i++){
System.out.println("The value of the alternate is :"+alternate[i]);
}
ArrayList<String> AlternateNew = new ArrayList<String>();
for(int i=1;i<keyword.length;i++){
if(keyword[i].equals(keyword[i-1])){
AlternateNew.add(alternate[i-1]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
String[] alternatenew = AlternateNew.toArray(new String[AlternateNew.size()]);
System.out.println("The length of the array is :"+alternatenew.length);
for(int i=0;i<alternatenew.length;i++){
System.out.println("the value of the alternatenew :"+alternatenew[i]);
}
}catch (Exception e){
System.out.println("there is an error :"+e);
}
}
}
The following is the csv file
Keyword,Alternate
ego kit,baby doll
ego kit,garage park
ego kit,random beats
galaxy tab,venus
galaxy tab,earth
galaxy tab,sun
What I am trying to do is compare elements and store it in an arraylist and display the results, but when last element is getting compared i.e 'galaxy tab' is getting compared to an empty field after last 'galaxy tab', it is not storing the previous result in the arraylist which is 'sun'
The following is the result of the program :
The value of the alternate is :baby doll
The value of the alternate is :garage park
The value of the alternate is :random beats
The value of the alternate is :venus
The value of the alternate is :earth
The last element is not getting stored in the arraylist.
Do not understand why? New to Java programming.
This section has a few problems also present throughout
AlternateNew.add(alternate[0]);
for(int i=1;i<keyword.length;i++){
if(keyword[i]==(keyword[i-1])){
AlternateNew.add(alternate[i]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
The naming convention in Java is to start with a lowercase letter for a variable name (unless it is a constant), which is why object AlternateNew is highlighted as if it were a class name.
The else if block tests the opposite of the same condition as its if. You could comment out if(!(keyword[i]==(keyword[i-1])), delete, or replace it with a more readable reminder comment, and the result would be the same.
AlternateNew.add(alternate[i]); happens regardless of this condition, in either branch of the if, so either remove the if statement entirely or fix some typo.
As for your actual [edit: original] question, I can't find anything wrong. Are you sure you didn't forget to save the csv file? I ran it using a text file and got output contrary to your post!

Categories

Resources