I would like to know how to split a field through array using Java. For example we have GLaccount like AAAA-BBBB-CCCC and we would like to split each component and store it in an variable however the GLaccount may have AAAA-BBBB (no third component) so in this case variable segment3 throws NULL POINTER exception so I am not sure on how to fix this since I am new to Java.
String GL = getOwner().getGL("GLACCT");
String segment1 = GL.split("-")[0];
String segment2 = GL.split("-")[1];
String segment3 = GL.split("-")[2];
Using split("-" ) will give you an array of strings.
before using array value, you can check the size of array that if it contains enough elements to use..
String GL = getOwner().getGL("GLACCT");
String[] array=GL.split("-");
String segment1 = array[0];
String segment2 = array[1];
//check if array have 3rd element
if(array.length >2)
String segment3 = array[2];
else
System.out.println("No third element") ;
Use split method (once) and check returned array length :
String[] values3 = "AAAA-BBBB-CCCC".split("-");
// values.length == 3
String[] values2 = "AAAA-BBBB".split("-");
// values2.length == 2
import java.util.Arrays;
List<String> list = Arrays.asList(GL.split("-"));
With this code you do not need to think if you have 2,3 or 10 strings, and to add new if for every new one.
Related
I am writing program to eliminate vowels in a String. What I want to do is check if the value of the character in the string is a Vowel. If it is false I want to store it in another array as follows:
if(isVowel(char_str[i]) == false) {
temp[index] = char_str[i];
index = index + 1;
}
I get an array out of Bounds exception for the 2nd line. I have initialised both the arrays as follows:
String str="Education";
char char_str[]=str.toCharArray();
char temp[] = {};
Can someone explain exactly what I am doing that is causing the error. I am a bit out of touch with the working of arrays in Java.
You cannot add an element to an array like this without specifying the array length. You can use ArrayList instead to add new elements without specifying the length. So either initialize the array length like this -
char temp[] = new char[100]; // Assuming 100 is the highest length
or declare an ArrayList like this -
List<Character> temp = new ArrayList<Character>();
You can add a new element to an ArrayList by using the add method.
temp.add(char_str[i]);
You are attempting to access an element of an empty array.
This line
char temp[] = {};
Creates an empty array - one with no elements.
So this
temp[index] = ...
Will explode because there are no positions to assign a value to.
Allocate some space, eg:
char temp[] = new char[str.length()];
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.
ArrayList<String> str = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
str.add(s1);
str.add(s2);
I want to compare a string to one of the elements of the array.
String b = "Test1";
b.equals(str[index??]);
How can i get the index of str?
It's an arrayList. Therefore, to store a value of the array with a certain index, use this:
ArrayList.get(index);
Now, you can make this equal to a variable like this:
String mStr = ArrayList.get(index);
If I have an arrayList with the values "1, 2, 3, 4" it's important to note, index 0 is the value 1.
ArrayList.get(0) //HERE, THE INDEX IS ZERO, MEANING THE VALUE OF THE ARRAY LIST WOULD BE 1
Output:
1
That is easily confused; index 0 = first value. Just be sure to use the get() method.
To further compare strings, set that values equal to strings:
String FIRSTSTRING= ArrayList.get(0);
String SECONDSTRING= ArrayList.get(1);
Here, I am comparing the first and second values of the array list.
If you found this helpful, mark it as best answer. If you need more help, feel free to ask me, I am always happy to help!
{Ruchir}
You want List.get(int) (where int is the index). For example,
List<String> al = Arrays.asList("Test1", "Test2");
System.out.println(al.get(0).equals("Test1"));
the output is
true
You can try something like this
ArrayList<String> str = new ArrayList<String>();
...
boolean found = false;
for(String string : str)
found =b.equals(string);
Other than that,you can use get method of list.
You can use indexOf() method.
ArrayList<String> str = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
str.add(s1);
str.add(s2);
System.out.println(str.indexOf("Test1"));
If you want to use the str.get(index) method and then check use a loop, But I find this more complicated.
for(int i = 0; i < list.size(); ++i)
if(list.get(i).equals("rtes"))
return i;
Use Binary Search if your Array is sorted. Otherwise, just go linearly in the arraylist, and compare the values.
in your case:
boolean find = false;
for(i=0;i<str.length;i++){
if(str.get(i) == b){
find = true;
break;
}
}
I have a small issue when I run into while using arraylists in Java. Essentially I am hoping to store an array in an arraylist. I know that arraylists can hold objects, so it should be possible, but I am not sure how.
For the most part my arraylist (which is parsed from a file) is just holding one character as a string, but once in a while it has a series of characters, like this:
myarray
0 a
1 a
2 d
3 g
4 d
5 f,s,t
6 r
Most of the time the only character I would care about in the string residing at position 5 is the f but occasionally I may need to look at the s or the t as well. My solution to this is to make an array like this:
subarray
0 f
1 s
2 t
and store subarray in position 5 instead.
myarray
0 a
1 a
2 d
3 g
4 d
5 subarray[f,s,t]
6 r
I tried to do this with this code:
//for the length of the arraylist
for(int al = 0; al < myarray.size(); al++){
//check the size of the string
String value = myarray.get(al);
int strsz = value.length();
prse = value.split(dlmcma);
//if it is bigger than 1 then use a subarray
if(strsz > 1){
subarray[0] = prse[0];
subarray[1] = prse[1];
subarray[2] = prse[2];
}
//set subarray to the location of the string that was too long
//this is where it all goes horribly wrong
alt4.set(al, subarray[]);
}
This isn't working the way I would like though. It won't allow me to .set(int, array). It only allows .set(int, string). Does anyone have suggestions?
The easiest approach would be to have an ArrayList of ArrayList.
ArrayList<ArrayList<String>> alt4 = new ArrayList<ArrayList<String>>();
However, this probably isn't the best solution. You may want to rethink your data model and look for a better solution.
Just change alt4.set(al, subarray[]); to
alt4.add(subarray);
I assume alt4 is another defined ArrayList<String[]>. If not, define it as below:
List<String[]> alt4= new ArrayList<String[]>();
or
ArrayList<String[]> alt4= new ArrayList<String[]>();
My guess is that you are declaring alt4 as List<String> and that's why it is not letting you set an array of String as a list element. You should declare it as List<String[]> and is each element is only singular, simply set it as the 0th element of the String[] array before adding it to the list.
You could switch to:
List<List<Character>> alt4 = new ArrayList<List<Character>>();
May be this is what you want to get
public class Tester {
List<String> myArrays = Arrays.asList(new String[] { "a", "a", "d", "g", "d", "f,s,t", "r" });
ArrayList<ArrayList<String>> alt4 = new ArrayList<ArrayList<String>>();
private void manageArray() {
// for the length of the arraylist
ArrayList<String> subarray = new ArrayList<String>();
for(int al = 0; al < myArrays.size(); al++) {
// check the size of the string
String value = myArrays.get(al);
int strsz = value.length();
String prse[] = value.split(",");
// if it is bigger than 1 then use a subarray
if(strsz > 1) {
for(String string : prse) {
subarray.add(string);
}
}
// set subarray to the location of the string that was too long
// this is where it all goes horribly wrong
alt4.set(al, subarray);
}
}
}
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 :)