sender.sendMessage("Your referal code is: " + codestring[ArrayUtils.indexOf(namestring, value )]);
the value is equal to "name" plus a random number, how can i make this work without knowing the second part of this string array?
iterate through array and check for startsWith()
for(int index = 0 ; index < array.length ; index ++){
if(array[index].startsWith(key)){return index;}
}
return -1; // not found
I didn't understand what you asked, but if you're trying to find a String, knowing only the first characters, you might use a regular expression to check, like:
for(String string: arrayOfStrings){
if(string.matches("beginningOfString^[1-9]")){
// your code
}
}
Related
how to get the sum of no which contains 8 digit in array? For example we take input from user and stored in array i.e. 33,6,8,95,123,88 so the sum will be 8+88=96 ......So how to find out the array contains 8 digit .Whats the logic behind this ...can anybody explain this?
If you facing this kind of problem try to divide it into small parts and then try to solve them. In the end they will exhaustively solve the big problem.
By the way You can do this in 2 ways in java.
Split number into digit using modulus (% ) operator.
for ( int I = 0; i<arr.length ; i++){
value = arr[i];
while( value > 0 ){
if ( value%10 == 8 ){
// it contains 8.
// add arr[i] to total and break the loop
}
Value= value/10;
}
}
eg :- 108%10 = 8
convert your number in to String and use String#toCharArray() to
split it.
String value = String.valueOf( arr[i] ); // convert it to char array
Char [] digitList = value.toCharArray(); // add separate digit to char array
And then check the char array has digit 8.
For more on spiting digits view this question's answers.
String myName[] = {"Mouse","Laptop","Facebook","Logitech"};
// print the first character
System.out.println(myName.charAt(0));
// print the second character
System.out.println(myName.charAt(1));
// print the last character
int lastPos = myName.length() - 1;
System.out.println(myName.charAt( lastPos ));
/*any one can explain to this noob? It's telling me to change to length, but that's not what I want. Basically what I want is to go through each character of string. */
You are using String methods on an array. To access the characters in the strings, you need to first get one of the String objects sitting in that array. Doing myName[0].charAt(0) for example will give you the first character of the first String in the array. If your intention is to do something with each character in each string in the array, you should use a loop like so:
for (int i=0; i<myName.length; i++){
for (int j=0; j< myName[i].length(); j++){
myName[i].charAt(j); // Do something with ths value, I am just getting it here.
}
}
You have created an Array of Strings where each element in that array is a "String". So, you can't use charAt to the array.
charAt(index) by it's name - you can think (give me the character at position index).
So, first you need to go to the particular "String" and then say "give me the character at position 'x' ".
So, if you want to go to "Facebook", then say hey "give me the element of the array at position 3 which is index 2" using:
myName[2];
store it in say variable str which needs to be a "String" :
String str = myName[2];
Then, you can use charAt(x) on str using :
for(int i =0 ; i<str.length() ; i++){
System.out.println(str.charAt(i));
}
You have initialized an array of string.Later if u want to access them you cannot directly use myName simply. Because its a container which has many memory locations in which data is stored. So by just using myName is not possible instead it should be followed by its index (ie, myName[i] pass 0,1,2.. in place of i). See the modification of ur program below. May be u can understand it.
public class ArrayDemo {
public static void main(String[] args) {
String myName[] = {"Mouse","Laptop","Facebook","Logitech"};
for(int i=0;i<=myName.length()-1;i++){
// print the first character
System.out.println(myName[i].charAt(0));
// print the second character
System.out.println(myName[i].charAt(1));
// print the last character
int lastPos = myName[0].length() - 1;
System.out.println(myName[i].charAt(lastPos));
}
}
}
I am trying to place spaces in between a number that has been entered in a textfield. I am using the following code:
for(int i = 0; i <= 2; i++)
{
char cijfer = tf1.getText().charAt(i);
char getal1 = tf1.getText().charAt(0);
char getal2 = tf1.getText().charAt(1);
char getal3 = tf1.getText().charAt(2);
}
String uitvoerGetal = getal1 + " " + getal2 + " " + getal3;
I suppose I don't understand the charAt() function yet, does anyone have a link explaining it in a way so I might be able to make this work too? Thanks in advance!
Example:
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
This produces the following result:
a
In more Detail From java docs
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
If the char value specified by the index is a surrogate, the surrogate value is returned.
Specified by:
charAt in interface CharSequence
Parameters:
index - the index of the char value.
Returns:
the char value at the specified index of this string. The first char value is at index 0.
Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
In straight words You can't. You can't add space in int datatype because int is meant to store the integer value only. Change int to String to store the space in between.
Okay, let's see what's wrong with your code...
Your for-loop is 1-based instead of the standard 0-based. That's not good at all.
You're attempting to assign a char to a String (3 times), the first call to charAt is correct, but for some reason you then switch to using a String?
Finally you're attempting to assign a String to an int, which is just completely nonsensical.
You have a number of problems, but well done on an honest attempt.
First up, the indexes in a string are zero-based, so charAt(0) gives you the first character, charAt(1) gives you the second character, and so on.
Secondly, repeating all your calls to charAt three times is probably unnecessary.
Thirdly, you must be careful with your types. The return value from charAt is a char, not a String, so you can't assign it to a String variable. Likewise, on the last line, don't assign a String to an int variable.
Lastly, I don't think you've thought about what happens if the text field doesn't contain enough characters.
Bearing these points in mind, please try again, and ask for further help if you need it.
Try following code
String text = tf1.getText(); // get string from jtextfield
StringBuilder finalString = new StringBuilder();
for(int index = 0; index <text.length(); index++){
finalString.append(text.charAt(index) + " "); // add spaces
}
tf1.setText(finalString.toString().trim()) // set string to jtextfield
I have a two Dimensional Object array (Object[][] data) that holds pairs of products-prices.
I try to pass these values to a Map with the following way.
private String myPairs = "";
private String[] l, m;
for (int i=0; i<data.length; i++){
myPairs += (String)data[i][0] + ":" + String.valueOf(data[i][1]) + ",";
}
Map<String, Double> pairs = new java.util.HashMap<>();
l = myPairs.split(",");
for (int i=0; i<l.length; i++){
m = l[i].split(":");
pairs.put((String)m[0], Double.parseDouble((String)m[1]));
}
I get a java.lang.ArrayIndexOutOfBoundsException. What's the wrong I have done?
Try
for (int i=0; i<l.length-1; i++){
m = l[i].split(":");
pairs.put((String)m[0], Double.parseDouble((String)m[1]));
}
You problem is here:
pairs.put((String)m[0], Double.parseDouble((String)m[1]));
The first for loop creates a string that ends with a ,. For example "foo:0.1,bar:0.2,".
Then, you split by ,. So, the above example will return ["foo:0.1"; "bar:0.2"; ""]. Note the empty string value, due to the last , of the string.
Finally, for each value, you split by :. It works for the first two values (i.e. ["foo"; "0.1"] and ["bar"; "0.2"]), but the last one will be a 1-value array, containing an empty string: [""].
When trying to access the second value of the array (i.e. the index 1 since arrays are 0-based indexed), the ArrayIndexOutOfBoundsException get thrown.
Several solutions:
In the first loop, put a condition to add the , or not:
myPairs += (i == 0 ? "" : ",") + (String)data[i][0] + ":" + String.valueOf(data[i][1]);
OR Just after your first loop, remove the last char of the string:
myPairs = myPairs.substring(0, myPairs.length() - 1);
OR In the second loop, don't go until the last value, but only until the n-1 one:
for (int i=0; i<l.length - 1; i++)
OR even better, only if you don't need the string representation you're building in the first loop, replace all your code by:
for (int i=0; i<data.length; i++) {
pairs.put((String)data[i][0], Double.parseDouble((String)data[i][1]));
}
When the first for-loop ends, you have all the pairs separated with ',' and an extra ',' in the end. So, l.length is the number of pairs plus one. Though, this shouldn't produce an error so far.
The problem is that when you split every pair on ':', the last element of l is equal to a blank string.
So the splitting produces an 1-element-array, containing a blank string. The error occures because you ask for m[1].
Try not adding the ',' after the last element of the pairs, and the problem should be solved.
I hope this helps :)
The last element in the split of ,s is empty (because you say + "," on the last iteration of the first loop), so skip the last element in the second loop.
for (int i = 0; i < l.length-1; i++)
{
m = l[i].split(":");
pairs.put((String)m[0], Double.parseDouble((String)m[1]));
}
Also note that if the supplied strings contains :s or ,s, your algorithm would probably throw an exception too.
Note - A way better way (and to avoid the above) would just be to do it in the first loop, something like:
for (int i = 0; i < data.length; i++)
{
pairs.put((String)data[i][0], Double.parseDouble((String)data[i][1]));
}
I have an ArrayList which contains duplicate values at diff diff index.
for example {"Indian","American","Chinese","Australian","Indian","Russian","Indian"}
as u can see the value - "Indian" exists at index - 0, 4 & 6.
I need to know all these indexes where "Indian" exists and create an arrayList of that.
Here is my code:
public void filter(){
categoryArray = Arrays.asList(category);
for(String k : category){
//Log.v("filter", filterTerm);
if(k.equals(filterTerm.toLowerCase()))
{
int p = categoryArray.indexOf(k);
Log.v("index of categArr", ""+p);
String id = Integer.toString(p);
indexes.add(id);
}// end of if
}// end of for
Here I get how many times duplicate occurs by getting the size of indexes(ArrayList)
but when I check the values . Its one value at all index since in the method : indexOf() it always brings the index of first value that it finds in the Array.
So if duplicate exists at index - 2,5,7
I get the array size of index as 3.
But the values are {2,2,2,};
This is a situation where an index-based for loop is more appropriate than enhanced for loop that you're using, as what you need to grab is the index.
You can base all your work on the original array rather than converting it to a list, and I suspect you were going for case-insensitive match.
public void filter(){
for(int i=0; i<category.length; i++){
if(category[i].equalsIgnoreCase(filterTerm))
{
String id = Integer.toString(i);
indexes.add(id);
}
}
}
If you have an ArrayList rather than an array, of course similar code will work, but using list.get(i) instead of category[i].
You need to know which index in the array you are currently at, not the first index where it is to be found. To keep track of that, put
int i = 0;
before the loop, and at the very end of the loop put
i++;
Then the variable i tells you where you have found the value, so you can add i to the indexes list.