There is this problem that i have been stuck with for hours.
I'm trying to check an ArrayList for a specific String.
This is the ArrayList i am checking:
public ArrayList getAllowedPlayers() {
return this.allowedPlayers;
}
The username's get added in lower case to this list.
Then this is what i use to check if the player typing the command is on the list:
boolean addedToSSList = data.getAllowedPlayers().contains(astring[0].toLowerCase());
"data" refers to the ArrayList of the username that has been entered (astring[0]). Which is in another class.
Then i use a print to chat message to check if the boolean turns true or false, which always returns false in my case.
icommandsender.sendChatToPlayer("addedToList: "+addedToSSList);
However, i can see that the username entered is added to the list with:
icommandsender.sendChatToPlayer("Allowed players: "+data.getAllowedPlayers())
The player from icommandsender is the person using the command to see if he is on the ArrayList.
So basically:
I can see that the Username i am entering is on the ArrayList (in lowercase). The astring[0] is this username in lowercase that i entered. But my boolean method will still return false.
Try this:
boolean addedToSSList = data.getAllowedPlayers().contains(astring[0].toLowerCase().trim());
May be you have some trailing spaces in your string.
EDIT:
public boolean findString(String s, ArrayList<String> al){
for (String str : al){
if (str.equalsIgnoreCase(s)){
return true;
}
}
return false;
}
and then you can find like
findString("myString", yourArrayList);
Related
After reading some other similar questions, I found that you cannot use a switch statement to check for more than one .contains tasks that result in different outcomes. I don't want to keep repeating if(string.contains("") for a single string. How else can I minimize the amount of .contain statements or is there actually a way I can implement a switch?
Using for loop to iterate through words to archive multiple .contains check.
First, create a class that validates your string input.
public class StringValidator {
String[] words = new String[]{"apple", "banana", "orange"};
public boolean isMatchAll(String input) {
for (String word : words) {
if (!input.contains(word)) {
return false;
}
}
return true;
}
}
Then call StringValidator.isMatchAll to check whether your string input is match all words
StringValidator stringValidator = new StringValidator();
String input = "I like apple, banana and orange.";
boolean isMatch = stringValidator.isMatchAll(input); // true
You could use a switch statement, but it would need to be paired with a loop that cycles multiple times for each word that needs to be matched.
Consider the following code that does the same thing, but with only a single contains statement written in code. The trick is that we simply create a list of words that need to be matched, and we pass your string and those words into a helper method which returns true if all the words matched:
//Sample list of words to match
String[] words = new String[]{"some", "example", "words"};
//Sample text to check
String yourText = "This is an example of some words to check for";
//Now we call our helper method containsList(yourText, words)
if (containsList(yourText, words)){
System.out.println("All words found");
}
else{
System.out.println("Not all words found");
}
And the following helper method is all the code we need, it simply uses a for loop to check each word and return true of false:
public static boolean containsList(String yourText, String[] listOfWords){
for (String word : listOfWords)
{
if(yourText.contains(word) == false)
//Break as soon as a match is not found
return false;
}
//Return true if all words in the words list were found
return true;
}
The result from our sample text is true and will print out "All words found".
Note that this may not a very efficient solution for large data sets, but you have not indicated in your question that you are working with large data, and this will work just fine in most cases.
I am currently working on when a user input a string, then my program will return the search result based on the inputted string. (In this example is "ca")
In the code below, I am only manage to make my program to return all the results which contains lowercase "ca" only.
However, I would like to convert "ca" to all Upper Case while still performing "contains" Regex when returning the search result. Which means, no matter the case is "ca" or "CA", all the results which conatins "CA" will be returned.
May I know how should I modify the code below? Thanks in advance.
public boolean matches( courseList p )
{
return p.getName().contains("ca");
}
Just change your whole text to lower/upper case:
public boolean matches( courseList p )
{
return p.getName().toUpperCase().contains("CA");
}
or
public boolean matches( courseList p )
{
return p.getName().toLowerCase().contains("ca");
}
I am not sure what to do but I can't print anything with this. I am beginner in programming and kind of lost right now.
So the question is what I need to put in the String integer = ""; to make this print something? I am using java. Thanks for help.
package myproject;
public class broke {
public static void main(String[] args){
boolean success = false;
String integer = "";
if(integer.indexOf("2") == 3){
success = true;
}
if(success){
System.out.println(integer);
}
}
}
Any string which has 2 at index, 3 will make the condition, integer.indexOf("2") == 3 true. Note that the index starts from 0 in a string.
Demo:
public class Main {
public static void main(String[] args) {
boolean success = false;
String integer = "543210";
if (integer.indexOf("2") == 3) {
success = true;
}
if (success) {
System.out.println(integer);
}
}
}
Output:
543210
In the string, 543210, the index of 5 is 0 and starting with this index, the index of 2 is 3.
your program will only print when success is true, since the statement, if(integer.indexOf("2") == 3) is false(integer is empty), success will be false, thus System.out.println(integer); will not be executed.
You're creating a String variable called "integer", and setting it's value to "" (an empty string).
System.out.println(integer);
The above snippet, if not for the weird if statement.. would print your string.. but your string is empty, so that printing would just consist of a \n being sent to System.out.
The reason nothing is printing is because the method call "string.indexOf("2")" returns -1 (indicating the character "2" was not found).
I saw in your comment you tried this with the string "3333", and again, expectedly, the character "2" would not be found.
I ran your code with setting String integer = "2", and it worked fine.
Maybe your confusion is how the indexOf() method, belonging to the String class, works. It returns the first index where the value passed in as a parameter occurs.
Why the function always return false even the buffer is true,
here is the code:
public class getCredentials {
User login = new User();
public boolean akses(String id, String password){
boolean buffer=false;
for (int i=0;i<login.sizeArrayList();i++){
buffer = login.getId(i).equals(id) && login.getPassword(i).equals(password);
}
return buffer;
}
}
you have an issue with the logic of the akses method,
that method can return false if the list is empty, because is returning the value of the initialization,
but also will return true if and only if, the id and password are correct for the last user in the list...
you dont need to iterate the whole list to validate an user actually.\
hpw to fix it
using java 8 you can stream the list, then filter using the credentials, then
check that the list is not empty
find any and if not found return null
example:
public boolean access(String id, String password){
User x = login.getArrayList().stream()
.filter(p -> login.validateId(id) &&
login.validatePassword(password))
.findAny().orElse(null);
return x != null;
}
You can update the akses method like that :
public boolean akses(String id, String password){
boolean buffer=false;
for (int i=0;i<login.sizeArrayList() && !buffer;i++){
buffer = login.getId(i).equals(id) && login.getPassword(i).equals(password);
}
return buffer;
}
(add !buffer in your loop condition)
As a previous answer has said: Assuming you have three users, and the second one is the one you are searching for.
The initialization before the loop will set "buffer" to false.
The first iteration of the loop will set "buffer" to false.
The second iteration will set "buffer" to true.
The third iteration will set "buffer" to false.
Then, the current value of "buffer" (which is "false") will be returned.
A correct bit of code would look like this:
public class getCredentials {
User login = new User();
public boolean akses(String id, String password){
for (int i=0;i<login.sizeArrayList();i++){
if(login.getId(i).equals(id) && login.getPassword(i).equals(password)) return true;
}
return false;
}
}
An even better implementation would use a hash map or a database (with an index over the username column).
The method returns the test of the last entry of the list. Is this intentional? I assume not. Maybe you like to write something like
buffer |=
If this is what you want, it is sufficient to return true immediately upon the first match.
I'm having ArrayList Contains of String. I would like to check whether the character is present in the arraylist. I'm using the following code.
if(list.toString.contains(char))
{
// enter code here
}
Can i use this toString() method. What is the drawback?
It would be a really bad idea to use List.toString() and search that. Your code should probably look something like this :
Iterator it = list.getIterator();
char searchChar = 'S';
while (it.hasNext())
{
String s = (String) it.next();
if ( s.contains(searchChar) )
{
//Found the char!
}
}
No you cannot go ahead with arraylist.toString(), as it will not provide string representation of contents in String.
Better approach is to iterate over list and check, as below.
for(String detail:listString){
if(detail.contains('X')) //replace 'X' with your character
{
// do somethng
}
}
Try this,
Arrays.toString(inputList.toArray()).contains(searchValue);
list.toString() gives you a string representation of a list and thus it contains more characters then just the concatenated list elements
[stringElement1, stringElement2, ... ]
Therefore your approach will not work if the character you are looking for is , , , [ or ].
And keep in mind that this string representation is implementation specific. It might not work for other list implementations than ArrayList
I would recommend to write a method linke this:
private boolean listElementContains(List<String> list, String subString){
for(String element : list){
if(element.contains(subString)){
return true;
}
}
return false;
}
You can call toString() on any Java Object. List is an Object which contains (you guessed it) a list of other Objects. Therefore, you can also call toString() on each Object contained within the List. You should read about inheritance in Java.
In your particular case, you have a List of Strings. What you actually want to do is check each String in the List to see if the String contains a particular character. Topics you may want to read about include iteration, for loops, and for each loops.
If I understand this correctly, your code would look like this:
List<String> strings = new ArrayList<>();
//add strings to list
for (String string : strings) {
//Look for some character c
if (string.indexOf(c) >= 0) {
return true;
}
}
return false;
On the matter of list.toString, that simply returns a representation of the object as a string; it has nothing to do with the contents. Think of it like a label on a box of stuff that says "Junk." The box is labeled Junk, but you have no idea what's in it.
What's nearly certain is that toString will return a nonsense label for the object in memory. So to get at what's inside, you need to loop through the contents as shown above.
if(list.toString.contains(char))
String's contains() method won't take char as param, instead check with indexOf
Your code works, with little modifications.
A small example here:
List<String> list= new ArrayList<>();
list.add("test");
list.add("test2");
if (list.toString().indexOf('t') > -1) // True
{
System.out.println("yes there");
}
Note:
As a workaround, Make an char array and add your char in to that array and then use contains method.