ArrayIndexOutOfBoundsException error after split operation on string - java

I am very confused with ArrayIndexOutOfBoundsException I am getting. I can't make an array TempCity's values allocated after using split method.
String[] TempCity = new String[2];
cityNames = props.getProperty("city.names").split(",");
cities = new City [cityNames.length];
//I have also tried String[] TempCity without succes
for (int i = 0; i < cities.length; i++) {
System.out.println(TempCity[1]); //OK
TempCity = cityNames[i].split(":"); // returns String array, problem is when Strings look like "something:" and do not receive second value of array
System.out.println(TempCity[1]); //Error
try{
if (TempCity[1] == null){}
}
/* I was thinking about allocating second array's value in catch */
catch (Exception e)
{
TempCity[1] = new String();
//I'm getting Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: 1
}
try{
cities[i] = new City( TempCity[0], TempCity[1] );
...
Thanks for help!
For now, my solution involves creating another string array:
String[] temp = new String[2];
String[] tempCity = new String[2];
temp = cityNames[i].split(":");
for (int j = 0; j < temp.length; j++){
tempCity[j] = temp[j];
}

split() does not return trailing empty strings. You have to allow for this in your code.
Use the two-argument version of split() and pass a negative number as the second argument.
From the javadoc:
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.

It means that split() returned an array with a single element, and you're trying to access a second one. Evaluating TempCity.length will show you that it's '1'
Print out TempCity[0] and see what that is; it's going to be your entire input string (cityNames[i]).

Doing String[] TempCity = new String[2]; does not help if you are going to overwrite TempCity with something else.

Related

Java: Removing an empty Element from String Array [duplicate]

This question already has answers here:
Resize an Array while keeping current elements in Java?
(12 answers)
Closed 3 years ago.
I have an array String ar[] = {"HalloWelt", " "};, ar.length is 2.
It does register two values within "HalloWelt" on index 0, and a blank/empty string on index 1;
I wonder how can I remove empty space on the index 1 - > but also keep it as a String Array since it is necessary for next task. Or how to do bunch of conversions but end up with String Array in the end.
My attempt
public String[] arraysWhiteSpaceEliminator(String[] arr) {
int k=0; //Identify how big the array should be i.e. till it reaches an empty index.
for(int i=0; i<bsp.length;i++) {
arr[i].trim();
System.out.println(arr[i].isEmpty());
if(arr[i].isEmpty()) {
}
else {
k = k+1; //if the index isn't empty == +1;
}
}
String[] clearnArray = new String[k];
for(int s = 0; s<k; s++) {
clearnArray [s] = arr[s]; //define New Array till we reach the empty index.
//System.out.println(clearnArray [s]+" " +s);
}
return clearnArray ;
};
The logic is very simple:
Identify how big the clearnArray should be.
Iterate through original Array with .trim() to remove white Space and check wether isEmpty().
Add to the k if the index isnt Empty.
Create clearnArray with the k as size.
Loop through originial Array till k -> add all the items to cleanArray till k.
Issue: .trim() and .isEmpty() don't record that the index is empty. ?!
A solution with streams:
String[] clean = Arrays.stream(ar)
.map(String::trim)
.filter(Predicate.isEqual("").negate())
.toArray(String[]::new);
Note that this assumes none of the array elements are null. If this is a possibility, simply add the following stage before the map:
.filter(Objects::nonNull)
The problem with your code is that after counting to find k, you just write the first k elements from the original array. To solve the problem by your technique, you need to check each element of the input array again to see if it's empty (after trimming), and only write to the new array the elements which pass the test.
The code can be simplified using the "enhanced" for loop, since you don't need indices for the original array. (The variable i keeps track of the current index in the new array.) Note also that strings are immutable, so calling .trim() does nothing if you don't use the result anywhere. Your code also refers to bsp which is not defined, so I changed that.
int k = 0;
for(String s : arr) {
s = s.trim();
if(!s.isEmpty()) {
k++;
}
}
String[] cleanArray = new String[k];
int i = 0;
for(String s : arr) {
s = s.trim();
if(!s.isEmpty()) {
cleanArray[i] = s;
i++;
}
}
return cleanArray;
Calculate the number of non-null elements and create an array of that size, like
String[] strs = ...;
int count = 0;
for (int i = 0; i < strs.length; i++) {
if (strs[i] != null) count++;
}
String newStrArray[] = new String[count];
int idx = 0;
for (int i = 0; i < strs.length; i++) {
if (strs[i] != null) newStrArray[idx++] = strs[i];
}
return newStrArray;
You could also probably make this prettier using streams. However I haven't used streaming functionality in Java, so I can't help there.
Two things to note:
Unless you are serializing or the nulls are causing other problems, trimming the array just to get rid of the nulls probably won't have an impact on memory, as the size of an array entry (4 bytes) is very likely inconsequential to the memory block size allocated for the Array object
Converting first to an List and then back to an array is lazy and possibly inefficient. ArrayList, for example, will likely include extra space in the array it creates internally so that you can add more elements to the ArrayList and not have to create a whole new internal array.
in your method, create a new
List cleanedList = new ArrayList();
add iterate through ar[]ar[] = ["HalloWelt",""], and add only non-empty values to cleaned List....then return the array.
return cleanedList.toArray()
like below:
List<String> cleanedList = new ArrayList<>();
for(String s : arr) {
s = s.trim();
if(!s.isEmpty()) {
cleanedList.add(s);
}
}
return cleanArray.toArray();

How can I remove all non-numeric elements from an array?

I have a String array which contains both integer and non-integer elements, and I need to remove all the non-integer elements of that array.
Now I am only able to remove the non-integer content in a single string, but I need to remove the entire non-integer elements in an array.
My snippet as follows
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
Can anyone help me to achieve it?
You can achieve it by below code
Pattern p = Pattern.compile("\\d*");
String [] array=new String[]{"23","33.23","4d","ff"};
List<String> lst=new ArrayList<String>();
for (int i=0; i<array.length; i++) {
if(p.matcher(array[i]).matches()){
lst.add(array[i]);
}
}
System.out.println(""+lst);
Your original code is this:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
First, if you need to remove all non-integer character, you need to change your regex from "[^\d.]" to "[^\d]".
Yours will not remove dots character.
Then, you said:
Now I am only able to remove the non-integer content in a single
string, but I need to remove the entire non-integer elements in an
array.
Maybe I'm not getting this right, but isn't just a matter of looping while doing the same thing ? You didn't show us any code with loops, but perhaps your true problem is reassigning the modified value to the array ?
try this:
for(int i=0;i<strArray.length;i++){
strArray[i] = strArray[i].replaceAll("[^\\d]", "");
}
MAYBE you were doing something like this ? (this does not work):
for(String str: strArray){
str = str.replaceAll("[^\\d]", "");
}
That doesn't work because the modified string is not reassigned to the array, it is assigned to the new variable 'str'. So this code does not update the value pointed by the array.
replace all numbers - str = str.replaceAll("\\d", "");
replace all non-numbers - str = str.replaceAll("[^\\d]", "");
to do so in an array, iterate over the Array and do the replacment.
To remove all the non-integer values form a string you can try the following:
public boolean isInt(String s)
{
for(int i = 0; i < s.length(); i++)
{
try
{
Integer.parseInt(String.valueOf(s.charAt(i)));
}catch(NumberFormatException e)
{
return false;
}
}
return true;
}
Then you can iterate your array and remove the non-integer elements like this
for(int i = 0; i < arr.length; i++)
{
if(isInt(arr[i]))//remove the element
}
It would probably be easier to remove elements from a list than from an array. However, you can stream the elements of the array, remove invalid elements with flatMap, and then convert back to an array.
When using flatMap, each element in the input can produce zero, one, or many elements in the output, so we map the valid ones to singleton streams containing just that element, and the invalid ones to empty streams, thus removing them from the result.
String[] result = Arrays.stream(input)
.flatMap(a -> Pattern.matches("\\d+", a)?
Stream.of(a) : Stream.empty())
.toArray(String[]::new);
If your regex is working correctly, you already solved most of your problem. You only need to use your code in a for loop. You can try the code below:
public String[] removeNonIntegersFromArray(String[] array){
ArrayList<String> temp = new ArrayList<String>();
for (int i=0; i<array.length; i++) {
String str = array[i];
if(!str.matches(".*[^\\d]+.*")){
temp.add(str);
}
}
String[] result = new String[temp.size()];
result = (String[]) temp.toArray(new String[temp.size()]);
return result;
}
Edit: I refactored the code as it will delete whole array element which has non-integer.
Here is an idea,
Instead of replacing all non-int number, to find all integer and add them to a new string.
for(int i=0;i<str.length();i++)
{
if(Character.isDigit(str.charAt(i)))
new_str.append(str.charAt(i));
}

how to save and replace multiple string in specific Array index

I try to save multiple strings in Array by using ,
myStringArray[0] = String
, but it keep saying
array type expected found java.lang.string
than I use
myStringArray.add(0,String)
it works , but can not replace specific index , it append more and more string in this array
than I try
myStringArray.set(0, String)
throw error at begging , cause index[0] in empty
than I though
for(int i = 0 ; i < 5 ; i ++){ myStringArray[i]=i; } at begging than use myArray.set()
and it come back the first issue
help please
code
private String imageLocation;
imageLocation = image.getAbsolutePath();
ArrayList<String> imagesLocations = new ArrayList<String>();
if (cameraOption == 0){
imageButtonOne.setImageBitmap(resizePhoto);
imagesLocations.add(0,imageLocation);
}
if (cameraOption == 1){
imageButtonTwo.setImageBitmap(resizePhoto);
imagesLocations.remove(1);
imagesLocations.set(1,imageLocation);
}
Your definition of imagesLocations (which I assume is supposed to line up with myStringArray)
ArrayList<String> imagesLocations = new ArrayList<String>();
makes it an ArrayList<>, not an array of String. That would have been
String[] imagesLocations = new String[someArraySize];
You should probably review the javadocs for ArrayList.

How do I get string values from my jtable?

I have my table filled in with strings and I'm trying to access them. I've tried '.getValueAt' but it gives me an error.
code is
'if (dayOfTheWeek=="Thursday"){
int thursdayCOUNT=0;
String[] THURSDAYSHOW=null;
while (thursdayCOUNT<10){
THURSDAYSHOW[thursdayCOUNT] = (String) timetable.getValueAt(thursdayCOUNT, 3);
thursdayCOUNT=thursdayCOUNT+1;
}'
error is 'Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at my.UI.schedulerUI.jButton1ActionPerformed(schedulerUI.java:1401)'
Right now you are initializing your String[] to null. You need to make it a new String["Some number goes here"]
It looks like you are using 10 as your length of iteration, so that could be how big you make the array:
String[] THURSDAYSHOW= new String[10];
This then can be easily followed up with a for loop to replace your while loop. Here is a full example:
if (dayOfTheWeek.equals("Thursday")){
String[] THURSDAYSHOW= new String[10];
for(int i = 0; i < THURSDAYSHOW.length; i++)
{
THURSDAYSHOW[i] = (String) timetable.getValueAt(i, 3);
}
}
One last note, use .equals() when comparing Strings.

how do I ignore/delete values of an array in java

I have a list of words , there are 4 words, it cant contain more that 4 its just an example. I want to use just 2 of the words the rest of them should be ignored or deleted e.g :
String planets = "Moon,Sun,Jupiter,Mars";
String[] planetsArray = planets.split(",");
int numberOfPlanets = planetsArray.length;
the result i get is 4. How do i delete the rest of the words if my list contains more that 2 words ?
As suggested in your previous question, you can use
String[] fewPlanets = new String[]{planets[0], planets[1]};
Just make sure the planets array has 2 elements or more to avoid an ArrayIndexOutOfBoundsException. You can use length to check it: if (planets.length >= 2)
For a more sophisticated solution, you could also do this using System.arrayCopy() if you're using Java 1.5 or earlier,
int numberOfElements = 2;
String[] fewPlanets = new String[2];
System.arraycopy(planets, 0, fewPlanets, 0, numberOfElements);
or Arrays.copyOf() if you're using Java 1.6 or later:
int numberOfElements = 2;
String[] fewPlanets = Arrays.copyOf(planets, numberOfElements);
String planets = "Moon,Sun,Jupiter,Mars";
String[] planetsArray = planets.split(",");
if(planetsArray .length > 2){
String []newArr = new String[2];
newArr[0]=planetsArray [0];
newArr[1]=planetsArray [2];
planetsArray = newArr ;
}
Use Arrays.asList to get a List of Strings from String[] planetsArray.
Then use the methods of the List interface -contains,remove,add, ...- to simply do whatever you want on that List.
If you need to select the first 2 planets just copy the array:
String[] newPlanetsArray = Arrays.CopyOf(planetsArray, 2);
If you need to select 2 specific planets you can apply the following algorithm:
First, create a new array with 2 elements. Then, iterate through the elements in the original array and if the current element is a match add it to the new array (keep track of the current position in the new array to add the next element).
String[] newPlanetsArray = new String[2];
for(int i = 0, int j = 0; i < planetsArray.length; i++) {
if (planetsArray[i].equals("Jupiter") || planetsArray[i].equals("Mars")) {
newPlanetsArray[j++] = planetsArray[i];
if (j > 1)
break;
}
}
You could use an idea from How to find nth occurrence of character in a string? and avoid reading the remaining values from your comma separated string input. Simply locate the second comma and substring upto there
(Of course if your code snippet is just an example and you do not have a comma separated input, then please ignore this suggestion :)

Categories