how to save and replace multiple string in specific Array index - java

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.

Related

Split a field through array in java

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.

Getting Index of Arraylist in Java

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;
}
}

ArrayIndexOutOfBounds

I'm working on a fraction calculator using String.split() to get the terms split. The inputs are separated by spaces( 1/2 / 1/2)
String[] toReturn = new String[6];
result = isInputValid(expression);
toReturn = splitExpression(expression, placeToSplit[0]);
int indexOfUnderscore = toReturn[0].indexOf("_");
result = isInputValid(toReturn[0]);
if(toReturn[5] != null){
getOperator2(toReturn);
}
The error is in the if statement. toReturn[5] is out of bounds, because when two terms or less were answered split expression, which uses String.split() to split it at the spaces, doesn't create toReturn[5], even when I set values to toReturn[5]. If there is a way to tell if a field in an array exists, that could solve it, or if there is a way to tell how many terms are being put in. My program works for 1/2 + 1/2 * 1/2, but I haven't figured out how to tell if toReturn[5] exists.
Correctly:
result = isInputValid(expression);
String[] toReturn = splitExpression(expression, placeToSplit[0]);
int indexOfUnderscore = toReturn[0].indexOf("_");
result = isInputValid(toReturn[0]);
if(toReturn.length>5 && !"".equals(toReturn[5]) ){
getOperator2(toReturn);
}
the toReturn.length>5 part verifies that the array itself is at least 6 items long. Then you can check if that element is empty or not...
This is what it should be like.
Remove first line , String[] toReturn = new String[6];
update your third line,
String[] toReturn = splitExpression(expression, placeToSplit[0]);
And check this condition:
if(toReturn.length>5 ){ // use !toReturn[5].isEmpty() to check the empty string
getOperator2(toReturn);
}

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 :)

ArrayIndexOutOfBoundsException error after split operation on string

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.

Categories