Since I couldn't figure out an easy way to convert my string array into an integer array, I looked up an example for a method and here is what I ended up with:
private int[] convert(String string) {
int number[] = new int[string.length()];
for (int i = 0; i < string.length(); i++) {
number[i] = Integer.parseInt(string[i]); // error here
}
return number;
}
parseInt requires a string which is what string[i] is but the error tells me "The type of the expression must be an array type but it resolved to String"
I can't figure out what is the problem with my code.
EDIT: I'm an idiot. Thanks all it was obvious.
You're trying to read a string as if it were an array. I assume you're trying to go through the string one character at a time. To do that, use .charAt()
private int[] convert(String string) {
int number[] = new int[string.length()];
for (int i = 0; i < string.length(); i++) {
number[i] = Integer.parseInt(string.charAt(i)); //Note charAt
}
return number;
}
If you expect the string to be an array of strings, however, you left out the array identifier in the function prototype. Use the following corrected version:
private int[] convert(String[] string) { //Note the [] after the String.
int number[] = new int[string.length()];
for (int i = 0; i < string.length(); i++) {
number[i] = Integer.parseInt(string[i]);
}
return number;
}
You have an error in your code. Use this code:
private int[] convert(String[] string) {
int number[] = new int[string.length];
for (int i = 0; i < string.length; i++) {
number[i] = Integer.parseInt(string[i]); // error here
}
return number;
}
Your method's parameter is a String and not a String array. You cannot access elements in a String with string[i]. If you want to actually get a single character from a String, use 'String.charAt(..)' or 'String.substring(..)'. Note that charAt(..) will return a char but those are easy enough to convert to Strings.
Use Arrays.asList( YourIntArray ) to create arraylist
Integer[] intArray = {5, 10, 15}; // cannot use int[] here
List<Integer> intList = Arrays.asList(intArray);
Alternatively, to decouple the two data structures:
List<Integer> intList = new ArrayList<Integer>(intArray.length);
for (int i=0; i<intArray.length; i++)
{
intList.add(intArray[i]);
}
Or even more:
List<Integer> intList = new ArrayList<Integer>(Arrays.asList(intArray));
.#this is worked for me
Related
How to get a random value from a string array in android without repetition?
I have array in String.xml file as below -
<string-array name="msg">
<item>Cow</item>
<item>Pig</item>
<item>Bird</item>
<item>Sheep</item>
</string-array>
I am selecting random string by using following code -
String[] array = Objects.requireNonNull(context).getResources().getStringArray(R.array.msg);
String Msg = array[new Random().nextInt(array.length)];
Can anyone help me please? Thanks is advance...!
Can you just do something like this:
Collections.shuffle(copyOfArray);
Then loop through that?
for (int i = 0; i < copyOfArray.size(); i++) {
println(copyOfArray.get(i))
}
try this -
array = Objects.requireNonNull(context).getResources().getStringArray(R.array.msg);
//String msg = array[new Random().nextInt(array.length)];
LinkedList<String> myList = new LinkedList<String>();
for (String i : array)
myList.add(i);
Collections.shuffle(myList);
for (int i = 0; i < myList.size(); i++) {
String msg=myList.get(i);
}
Try this solution,
LinkedList<String> myList = new LinkedList<String>();
String[] words = { "Cow", "Pig", "Bird", "Sheep" };
for (String i : words)
myList.add(i);
Collections.shuffle(myList);
Then,
sampleText.setText(myList.pollLast());
pollLast() in LinkedList will retrieves and removes the last element of this list, or returns null if this list is empty.
try this.
int max = array.length() - 1;
int min = 0;
String Msg = array[new Random().nextInt(max - min + 1) + min];
First convert your String resource array to ArrayList
Fill value from current ArrayList to HashSet and convert that HashSet to newly ArrayList
Now shuffle that new ArrayList
Creating an app in which i want to get string from json but i have one key and multiple value so i don't know how to handle this.
"colours": "#fff600,#000000,#ffffff,#00000,#ff9900,#333333"
And want to use this color in different class:
final ValueAnimator colorAnimation = ValueAnimator.ofObject(new android.animation.ArgbEvaluator(), Color.RED, Color.BLUE,Color.WHITE,Color.YELLOW,Color.CYAN,Color.MAGENTA,Color.GREEN,Color.GRAY);
colorAnimation.setDuration(1400);
Put the value of colours in string variable and then split the string in following way and add it to an arraylist :
String[] arr = str.split(",");
ArrayList<String> arr1 = new ArrayList<String>();
for (int i=0; i<arr.length; i++){
arr1.add(arr[i]);
}
Get value of color and use string tokenizer with ',' delima like this:
StringTokenizer stringTokenizer = new StringTokenizer(colorValueString, ",");
Also it has stringTokenizer.nextToken to get the next color in string
You can get the value of colours as a string and then split the string into parts like this:
String colours = json.getString("colours");
Log.d(TAG, colours);
String items[] = colours.split(",");
for (String item : items) {
Log.d(TAG, item);
}
If you own the json
You should use JSONArray:
"colours": ["#fff600","#000000","#ffffff","#00000","#ff9900","#333333"]
And read it like
JSONObject json = ...;
JSONArray colorsArray = json.getJSONArray("colours");
for(int i = 0; i < colorsArray.length(); i++) {
String colorString = colorsArray.getString(i);
int color = Color.parseColor(colorString);
// you should probably also catch IllegalArgumentException for wrong input
}
If you don't own the json
You can read it as string and split around commas:
JSONObject json = ...;
String colorsString = json.getString("colours");
String[] colorStrings = colorsString.split(",");
for(String string : colorStrings) {
int color = Color.parseColor(string);
// you should probably also catch IllegalArgumentException for wrong input
}
I'm a beginner in Android.
I have created a edit text field where can I enter values from 0-9. Now, I have to get these values in an integer array.
example : entered values are 12345.
I need an array containing these values
int[] array = {1,2,3,4,5};
I need to know the way to do this. Kindly help.
Try this :
String str = edittext.getText.toString();
int length = str.length();
int[] arr = new int[length];
for(int i=0;i<length;i++) {
arr[i] = Character.getNumericValue(str.charAt(i));
}
You can use something like this:
int[] array = new int[yourString.length()];
for (int i = 0; i < yourString.length(); i++){
array[i] = Character.getNumericValue(yourString.charAt(i));
}
I am trying to remove special character from arraylist.
Not getting click how to do this?
I have 3 editfield and filling text after certain conditions
means when 1 is filled then another can be filled. now when i click to save this. this returns an array like [hello,abc,zbz] for fields
private List<String> hashtagData;
hashtagData = new ArrayList<String>();
String status_message = status.getText().toString();
String status_message2 = status2.getText().toString();
String status_message3 = status3.getText().toString();
hashtagData.add(status_message);
hashtagData.add(status_message2);
hashtagData.add(status_message3);
But I am trying to remove "[]".
Thank you if anybody can help.
Here try this:
ArrayList<String> strCol = new ArrayList<String>();
strCol.add("[a,b,c,d,e]");
strCol.add(".a.a.b");
strCol.add("1,2,].3]");
for (String string : strCol) {
System.out.println(removeCharacter(string));
}
private String removeCharacter(String word) {
String[] specialCharacters = { "[", "}" ,"]",",","."};
StringBuilder sb = new StringBuilder(word);
for (int i = 0;i < sb.toString().length() - 1;i++){
for (String specialChar : specialCharacters) {
if (sb.toString().contains(specialChar)) {
int index = sb.indexOf(specialChar);
sb.deleteCharAt(index);
}
}
}
return sb.toString();
}
Create regex which matches with your criteria, then loop through your list.
String myRegex = "[^a-zA-Z0-9]";
int index = 0;
for (String your_string : list)
list.set(index++, s.replaceAll(myRegex, ""));
can use below function to remove special character from string using regular expressions.
using System.Text;
using System.Text.RegularExpressions;
public string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}
I am trying to save the state in my Fragment through the use of Parcelable.
This lead to the following code when I wish to get back the a String array that I saved in the Parcelable:
public MyObject createFromParcel(Parcel in) {
titles=in.readStringArray(???);
}
Now readStringArray needs a parameter, a String[]... But why? It could just give the Strings that I stored in it. I don't know a priori how many there were, so this sucks. :(
The documentation says the following:
That is, nothing.
EDIT: If anyone has the same problem: I ended up using writeBundle()/readBundle() and putting my String[] into the Bundle.
Use createStringArray() instead of readStringArray(String[]). It will return the array you need.
Here is an implementation of this method from Android 4.1.2:
public final void readStringArray(String[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readString();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
So it writes values to given array. And returns nothing.
I think it might be useful to view these two methods, readStringArray(String[] val) and createStringArray() side by side:
Let's look at readStringArray(String[] val) method first. It requires a String[] as a parameter and might result in a NullPointerException if you pass a non-initialised array object (null). Also, you'll have to know exactly the length of the array (N), otherwise you'll get the RuntimeException thrown from the method:
public final void readStringArray(String[] val) {
int N = readInt();
if (N == val.length) {
for (int i=0; i<N; i++) {
val[i] = readString();
}
} else {
throw new RuntimeException("bad array lengths");
}
}
Oh the other hand, with createStringArray() you don't need to form and provide a String[] as a parameter, it will be formed for you by the method with the correct length too, so you don't have to worry about either NullPointerException or RuntimeException:
public final String[] createStringArray() {
int N = readInt();
if (N >= 0) {
String[] val = new String[N];
for (int i=0; i<N; i++) {
val[i] = readString();
}
return val;
} else {
return null;
}
}
All in all, as a result of this basic analysis we can jump to conclusions and say that the second method is better and safer..