private String[] userKeys;
userKeys = MHConstants.friendsModelDetails.keySet().toArray( new String[MHConstants.friendsModelDetails.size()]);
if(MHConstants.friendsModelDetails.size()>0 ){
for(int i = 0;i<MHConstants.friendsModelDetails.size();i++){
String username = userKeys[i];
System.out.println("userkey contains"+username);
}
String number=9;
THis prints
1
5
9
8
10
How can i get the position of the value which is equal to ''number'' and delete that from userskey...
thanks in advance.
You can try Apache Commons
userKeys = ArrayUtils.removeElement(userKeys , number);
Or just iterating through array and shifting elements can do the same.
Something like (Its ugly and not tried/tested)
String number = "9";
boolean flag = false;
int j;
int length = userKeys.length;
for (int i = 0; i < length; i++) {
if(number.equals(userKeys[i])){
flag = true;
j = i;
}
}
if(flag){
for(int i=j;i<length-1;i++){
userKeys[i+1] = userKeys[i];
}
userKeys[length] = null; // resetting the value
}
Consider using a List instead of an Array. Then use an Iterator which will allow you to remove the element.
List<String> values = ...;
Iterator<String> iterator = values.iterator();
while(iterator.hasNext){
String next = iterator.next();
if (number.equals(next))
iterator.remove();
}
Related
Here is an example of my array
List<Integer> sampleList = new ArrayList<>();
all values inside this array are:
sampleList = [1,2,3,4,5,6]
Basically I'm using for to loop each values from this array
for (int i = 0; i < sampleList.size(); i++) {
int to = sampleList.get(i);
if (norooms == to) { //norooms = 1
//display a toast
}
}
I want to check if position 0-5 are all equal to 1 but I cant achieve it. Any help
You can try something like this.
int editTextValue = 3; // Your edit text value
boolean isEqual = true;//Flag to check if all the values are equal or not.
for (int i=0; i<sampleList.size(); i++){
if (sampleList.get(i) != editTextValue){
isEqual = false;
break;
}
}
Then check the condition of isEqual after the loop is over and handle accordingly.
public Check {
int value;
int index;
boolean match;
// constructor, setters and getters
}
For about all the information you want:
public List<Check> checkValues(List<Integer> originalList, Integer testValue) {
List<Check> result = new ArrayList<>();
for ( int i = 0; i< originalList.size(); i++ ) {
result.add(new Check(i, originalList.get(i), originalList.get(i) == testValue);
}
return result;
}
This is 'a way' to do it. You'll have information on how many matches there were, which other values there were and on which index in your List they were found.
I'd use Java Streams, check out more on: Streams
Basically turns the list into a stream of elements and then you can process the data.
//To get only the elements equal to 1
sampleList.stream()
.filter((num) -> num == 1);
//to get a list of booleans whose value depends on the element being equal to 1.
List<Boolean> listBooleans = sampleList.stream()
.map((num) -> num == 1)
.collect(Collectors.toList())
filter uses a predicate to determine if the element matches a certain condition, in this case number == 1.
map transforms the stream of Integers into a Stream of booleans where the result is number == 1.
collect terminates the stream, with Collectors.toList transforms it into a List.
Hope this helps.
Arraylist<String> matchedValues = new Arraylist<>();
String editTextValue = edittext.getText();
String arrayValue;
boolean isEqual ;
boolean isEveryElementPresent = false;
for (int i = 0 ; i < sampleList.size() ; i++){
arrayValue = sampleList.get(i);
if(arrayValue.equals(editTextValue)){
isEqual = true;
matchedValues.add(arrayValue);
}else{
isEqual =false;
}
}
if(matchedValues.size() == sampleList.size()){
isEveryElementPresent = true;
}
static String[] TEST_NAMES = new String[]{"vectorTest",
"scalarMultiplicationTest", "columnVectorTest", "dotProductTest",
"matrixTest", "matrixMultiplicationTest", "selectRowTest",
"selectMaxTest", "indexOfMaxTest", "updateTest", "addItemTest",
"updateDatabaseTest"};
I want a loop that would iterate through this array and whenever it points at an index in the testNames array it should pass it as an 'E' on to another array and the final array should be passed to a 'resultString' variable which returns all 'E's to the database. This is what I have tried but it has errors cos they are incompatible types.
testNames = OOJavaBasics.TEST_NAMES;
ArrayList<Integer> zeroSubmission= new ArrayList<>();
for (int i = 0; i < testNames.length; i++) {
if (thirdLastLine.contains("OK (0 tests)") && testNames.equals(i)){
zeroSubmission.add('E');
resultString = zeroSubmission;
System.out.println(resultString);
}
}
The output should be the total number which is 12 of the array length in E like this 'EEEEEEEEEEEE'
You can do it using only a String instead of having a second array.
Try the following:
testNames = OOJavaBasics.TEST_NAMES;
String resultString="";
for (int i = 0; i < testNames.length; i++) {
if (thirdLastLine.contains("OK (0 tests)") && testNames[i].equals("wanted result")){ // do not compare an Array with an int in the .equals()
resultString += "E";
}
}
System.out.println(resultString);
Everytime you find the wanted result, you directly add an "E" to your resultString.
EDIT:
Referring to your last EDIT, the solution is very simple:
for (int i = 0; i < testNames.length; i++) {
resultString += "E";
}
Just loop through the array and add an E to the resultString in each iteration.
This is how I solved it
String E = "";
if (thirdLastLine.contains("OK (0 tests)")) {
System.out.println(thirdLastLine);
for (int i = 0; i < testNames.length; i++) {
E += 'E';
}
resultString = E;
System.out.println(resultString);
}
I am trying to populate a java string array with a variable. the variable contains values which I am reading in from a text file. every time a new value is stored in the array the current value is replaced by the new value.
the code below is what i have tried so far.
int n = 0;
String var1 = value;
String array[] = {var1};
String [] array = new String[n];
for (int i =0; i < n; i++) {
array[n++] = value;
}
Java has only fixed sized arrays; dynamically growing "arrays" are realized with List:
List<String> array = new ArrayList<>();
for (int i = 0; i < 42; ++i) {
String s = "" + i;
array.add(s);
}
for (String t : array) {
System.out.println(t);
}
String seven = array.get(7);
int n = array.size();
if (array.isEmpty()) { ... }
// In Java 8:
array.stream().sorted().forEach(System.out::println);
Using (fixed sized) arrays would be cumbersome:
String[] array = new String[];
String[] otherVar = array;
for (int i = 0; i < 42; ++i) {
String s = "" + i;
array = Arrays.copyOf(array, i + 1);
array[i] = s;
}
Here on every step a new array is created, the content of the old array copied.
Also notice that otherVar keeps the initial empty array.
Note that String[] a is the same as String a[]. The latter is only for compatibility to C/C++, and is less readable.
This will add a string indefinitely. When you read all the data from file you have to set isFileNotEnded = false
boolean isFileNotEnded = true;
List<String> array = new ArrayList<>;
while (isFileNotEnded) {
array.add("hello");
//stop here the infinite loop
}
Say I have a string, and I want to change the second "a" in that string to an "e".
String elephant = "elaphant";
I tried using String.replace(), but that replaces all the a's in the string, returning "elephent".
elephant.replace("a", "e");
Is there any loop or method I can use to accomplish this? Thank you all.
You could convert it to a char array, switch out the desired letter, then convert it back to String?
String elephant = "elaphant";
int index = -1;
int count = 0;
while(count < 2) {
index = elephant.indexOf("a", index+1);
count++;
}
if(index >= 0 && index < elephant.length()) {
char[] tmp = elephant.toCharArray();
tmp[index] = "e";
elephant = new String(tmp);
}
Or if you prefer StringBuilder
StringBuilder sbTemp = new StringBuilder(elephant);
sbTmp = sbTmp.replace(index, index+1, "e");
elephant = sbTmp.toString();
You need to get the index of the first occurrence of a letter.
Try using the indexOf method.
int myIndex = elephant.indexOf('a');
Once you have the index, use StringBuilder to replace the value. Something like:
StringBuilder sb = new StringBuilder(elephant);
sb[index] = myIndex;
elephant = sb.ToString();
Code:
String elephant = "elaphant";
//convert the string to array of string
String[] sp = elephant.split("");
int countA = 0;
boolean seenTwice = false;
String result = "";
for (int i = 0; i < sp.length; i++) {
//count number of times that a has been seen
if (sp[i].equals("a")) {
countA++;
}
// if a has been seen twice and flag seenTwice has not been see
if (countA == 2 && !seenTwice) {
result += "e";
seenTwice = true;
} else {
result += sp[i];
}
}
System.out.println(result);
Output:
elaphent
public boolean makeReservation(int id, AvilaNatalyPassenger request) {
boolean status = true;
ArrayList<Integer> inputValues = new ArrayList<Integer>();
for (int i = 0; i < 22; i++) {
for (int j = 0; j < 5; j++) {
id = seats[i][j];
if (id != -1) {
if (inputValues.contains(id)) {
status = false;
break;
}
else {
inputValues.add(id);
for(int a = 0; a < inputValues.size; a++)
seats[a] = inputValues[a];
}
}
}
}
return status;
}
This is what I have but its not correct. I need to add what I have in inputVaule arrayList into the array seats.
You can also look at the Java API: http://docs.oracle.com/javase/7/docs/api/index.html?java/util/ArrayList.html
public Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
So this is what you could do:
seats[a] = inputValues.toArray();
Furthermore you cannot use inputValues[a] since it is not an array. What you probably could do is
seats[a] = (inputValues.toArray())[a];
To answer your question, here is an example:
ArrayList<String> stock_list = new ArrayList<String>();
stock_list.add("stock1");
stock_list.add("stock2");
String[] stockArr = new String[stock_list.size()];
stockArr = stock_list.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Example is taken from here