Hi everybody im programming an application in Android and I don`t know what to do to get this that I am trying. I now that it is very simple but please help me!
Lets say that I have an array:
String coco[] = { "hi", "everybody", "superman", "batman" };
And also I have a:
String heroe = "superman";
Now I need to make a loop, method or whatever, that takes "heroe" and search if that value ("superman") its inside the array and then so if that value exist TRUE and if don`t exist FALSE.
Thank you guys.
The most comfortable way is to convert the array to a list and search then.
It is clean, short and expressive.
boolean isThere = Arrays.asList(yourArray).contains("needle");
for(int i=0;i<coco.length;i++)
{
if(coco[i].equals(heroe))
return true;
}
Here is a simple solution. It would be easier to use an ArrayList that can use .contains ()method.
for(int i = 0; i < coco.length; i++)
{
if(coco[i].equals(heroe))
{
// a match!
return true;
}
}
// no match
return false;
Simply iterate over the values in the array and compare them to the value you're looking for
public boolean arraySearch(String[] strArray, String key) {
for (String s : strArray) {
if (s.equals(key)) {
return true;
}
}
return false;
}
You can use this by calling arraySearch(coco, heroe); in your code.
Alternatively you could use the Arrays class and use:
boolean keyPresent = Arrays.asList(coco).contains(heroe);
you could do some thing like this:
for (String testcoco : coco)
{
if (testcoco.contains("superman"))
{
return true;
}
}
return false;
You can do like this.
Just take a variable which you want to search and iterate the array and use equals method.
String heroe = "superman";
boolean flag = false;
for(int index = 0; index < coco.length; index++)
{
Strin value = coco[index];
if(heroe.equals(value))
{
flag = true;
}
}
if(flag) {
//Exist
}
else {
//Not Exist
}
public boolean checkPresence(String desired)
for(String s:coco){
if(s.equals(desired)){
return true
}
}
return false;
Related
I need to use indexOf to find numbers inside a string, and it gives me the error:
Type mismatch: cannot convert from int to boolean.
public static boolean validPassword(String password) {
if(password.length() >= 8 ){
return true;
}
else if (password.indexOf("0")) {
return true;
}
return false;
}
Don't use index. You can use String.matches().
String str = "ksksks8ksksksksksks";
System.out.println(str.matches(".*\\d.*"));
Honestly though, if you can do it anyway you want, I would simply write a method as follows. Regular expressions are great for complicated patterns but they are also expensive in terms of processing.
public static boolean containsNumber(String str) {
boolean found = false;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
found = true;
break;
}
}
return found;
}
You could also modify the above and call it indexOf and iterate thru the characters using a regular for loop. Then returning either the location of the first digit or -1 just like the String version of indexOf().
And finally, for fun, you could use the Streams capability of Java 8+.
public static boolean containsNumber(String str) {
return str.chars().filter(Character::isDigit).count() > 0;
}
I am writing a text-based survival simulator that uses an array of Entitys. The Entity class contains data about each entity, such as energy, hydration, and morale. I'm starting to wrap up the project but I have a problem. In order to write a checkStatus() method, I need to have an if statement that checks for Entity[].isAlive on all entities, even if I don't know how long the array is. In short, how can I use an if statement to check for the value of all members of an array? I know I will probably have to use a for loop to iteratively check the members, with the array.getLength. So far I can only check variables in single classes. I have seen similar questions but they don't quite get what I'm looking for.
P.S. I'm using basic Java, with no frameworks or libraries.
Pseudo-code that demonstrates what I'm looking for
if Entity[ALL-MEMBERS].isAlive {
gameOver = true;
}
Java 6, 7, and 8:
public boolean areAllAlive(Entity[] entities) {
if(entities == null || entities.length == 0) {
return false; //?
}
for(Entity e : entities) {
if(!e.isAlive()) {
return false;
}
}
return true;
}
Java 8, using streams/functions:
public boolean areAllAlive(Entity[] entities) {
if(entities == null || entities.length == 0) {
return false; //?
}
return Arrays.stream(entities).allMatch(e -> e.isAlive());
}
First, since you probably don't know the number of Entities you are going to use before hand an ArrayList is probably a better choice. Then yes, you should use an enhanced for loop:
List<Entity> list = new ArrayList<>();
public void addEntities(){
//add Entities here
}
public boolean ifAlive(){
for (Entity e: list){
if (!e.isAlive()){
return false;
}
}
return true;
}
or something like that.
Assuming array is your entity's array, try this.:
for (int i = 0; i < array.length; i++) {
Entity entity = array[i];
if (entity.isAlive) {
gameOver = true;
//your code here
}
}
I'm trying to create a recall program that sends text messages to 200+ people and then searches an email that the replies are forwarded too.
This method is supposed to search the array list of replies that is built using another method, but it doesn't work correctly. It will only work if the very first message on the array list matches the very first number in the contact list.
Those are some other problems, but my main question here is why does it say that the code specifically inside of my for loop is dead code?
public static boolean searchForPhone(String phone){
CharSequence phoneN = phone;
for(int i=0;i<myMessages.size();i++){
if(myMessages.get(i).contains(phone)){
return true;
}
else{
return false;
}
}
return false;
}
This is your code, properly formatted:
public static boolean searchForPhone(String phone) {
for (int i = 0; i < myMessages.size(); i++) {
if (myMessages.get(i).contains(phone)) {
return true;
} else {
return false;
}
}
return false;
}
The construct flagged as Dead code is the i++ in the for-loop header. It is indeed dead code because the for loop's body unconditionally makes the method return. Therefore the "step" part of the for header is unreachable aka. dead.
The same fact makes your code perform incorrectly, BTW. Removing the else clause would be a big improvement.
Will this help?
public static boolean searchForPhone(String phone){
CharSequence phoneN = phone;
for(int i=0;i<myMessages.size();i++){
if(myMessages.get(i).contains(phone)){
return true;
}
}
return false;
}
Look you are looping over n-element list. When you get first element on the list you got if/else statement.
So you will HAVE TO either of 2 things, both of witch is return. So your program will exit on first element returned.
To make it simplier, your code is equal to:
CharSequence phoneN = phone;
if (myMessages.size() ==0 ){
return false;
}
return myMessages.get(0).contains(phone);
Try from Window > Preferences > Java > Compiler > Error/Warnings
Change Dead code (e.g 'if(false)') and Unnecessary 'else' statement to Error.
Your loop always returns from the function at the end of the first iteration. This makes i++ dead code since it never executes.
Anyway, remove the else clause to fix the code.
In the else part you need to continue to search. Else if your fist element is not the matching one will return false and not going to check other element.
public static boolean searchForPhone(String phone) {
CharSequence phoneN = phone;
for (int i = 0; i < myMessages.size(); i++) {
if (myMessages.get(i).contains(phone)) {
return true;
} else {
//return false this conditional return cause
// the complain it as dead code. Since for loop will become not
//loop
continue; // will search for other elements.
}
}
return false;
}
Now you can simplify this code to following because else part is not really necessary.
public static boolean searchForPhone(String phone) {
CharSequence phoneN = phone;
for (int i = 0; i < myMessages.size(); i++) {
if (myMessages.get(i).contains(phone)) {
return true;
}
}
return false;
}
I'm trying to make a boolean method, but it's not recognizing I have a return statement. What should I do?
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
return true;
}else{
return false;
}
}
}
Your code does not make sense. There is no point in having a loop if you're always going to run the code inside the loop exactly once. I think you must have misunderstood. What are you trying to do?
Assuming the method only has to return true or false if it is greater than equal to 3,
would recommend to keep it simple.
Also, Please Note:
Loop through the i=0 to i< rankHist.length incase the array contains less than 13 elements you will encounter an ArrayOutOfBoundException.
If it contains more than 13 elements, the output might be incorrect.
.
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<rankHist.length;i++){
if (rankHist[i]>=3){
return true;
}
}
return false;
}
I think what he wants is if every element in the 13 are >=3, he should return a true, else ways he should return a false.
public boolean isThreeKind( int rankHist[])
{
for (int i=0;i<=13;i++)
{
if (rankHist[i]<3)
{
return false; // Will return false if either of the element have value <3
}
}
return true; // Will return true only if all the 13 elements have value >=3
}
This is literally what your code is doing right now:
public boolean isThreeKind( int rankHist[]) {
return rankHist[0] >= 3;
}
That is it, and I am assuming this is not what you are attempting to do. So if you tell us what you are actually trying to accomplish we can help you more.
In java, You always gotta keep track of returning something EVERYWHERE the method can exit. If it can exit without hitting a return statement, you'll see that error.
So, for your code, to modify it and make it see it, you would need to have it say:
public boolean isThreeKind( int rankHist[]) {
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
return true;
}else{
return false;
}
}
return false;
}
Or true, if you would rather that.
You should avoid multiple return statement.
You can use a flag. Declare the flag outside the for loop, then assign the value accordingly, and do not miss the break statement.
Do it like that:
public boolean isThreeKind( int rankHist[]) {
boolean value = false;
for (int i=0;i<=13;i++){
if (rankHist[i]>=3){
value = true;
break;
}
}
return value;
}
This is a method in a spell checker. As the header explains, it should return true if and only if all the words added to the arraylist are found in the parent array, words. Otherwise it should return a false value. I've been fighting with this for a few hours and this is my current situation...
/**
* This method returns true if (and only if) all words in the
* given wordList are found in the dictionary.
*/
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(int index = 0; index < wordList.size(); index++)
{
if(words.contains(!wordList.contains(index)))
{
result = false;
}
result = true;
}
return result;
}
All I really need is a way to turn out a yes or no, but I'm lost.
Please try and work with the code given as this is an exercise to teach that code.
Thanks!
Your problem is here:
if(words.contains(!wordList.contains(index)))
!wordList.contains(index) is a boolean expression, so it always evaluates to either true or false. So you're actually checking if the words list contains true or false, not the word like you want. Replace it with if(!words.contains(wordList.get(index)) to check if the current word is found in the dictionary.
I would suggest a following solution: iterate wordList word by word, and for each word check if it's found in the dictionary. If not so, return false immediately. If you reach the end of the loop, return true.
Here could be another solution:
public static boolean allKnown(List<String> parent, List<String> child) {
List<String> temp = new ArrayList<String>(child);
temp.removeAll(parent);
return temp.isEmpty();
}
For example:
List<String> parent = Arrays.asList("w1", "w2", "w3", "w4");
List<String> childOk = Arrays.asList("w1", "w4");
List<String> childKo = Arrays.asList("w1", "xx");
System.out.println(allKnown(parent, childOk));
System.out.println(allKnown(parent, childKo));
Prints:
true
false
Take out result = true; - you don't want to reset the value to true at every step in the loop.
Also change wordList.contains to wordList.get (because you want to get the word at a specific index, not check if it's contained in wordList) and move the ! out (because you can't 'not' a string).
And you can also optimize by checking result's value in the for-loop condition (or simply returning directly in the if-statement).
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(int index = 0; index < wordList.size() && result; index++)
{
if(!words.contains(wordList.get(index)))
{
result = false;
}
}
return result;
}
If words really is an array and not an ArrayList, it doesn't have a contains method, you'll have to either have a double for-loop, or convert it to a list:
List<String> parentWords = Arrays.asList(words);
...
if (parentWords.contains(...))
Don't reset result to true after your if. Because like this the whole function will always return true.
A few tips:
Don't use ArrayList as a method parameter, always use the more abstract List (none of your code depends on ArrayList, so you can change the implementation later, if you like).
Iterate over List objects using the simplified syntax shown below.
You only need one word to be not in the words list to return false, so do exactly that (as shown below).
public boolean allKnown(List<String> wordList) {
for (String word : wordList) {
if (!words.contains(word)) {
return false;
}
}
return true;
}
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(String word : wordList)
{
if(!words.contains(word))
{
result = false;
}
}
return result;
}
Here is a simpler version :
public boolean allKnown(List<String> wordList) {
List<String> wordListCopy = new ArrayList<String>(wordList);
return !wordListCopy.retainAll(words);
}
PS : retainAll() removes from you wordList all of its elements that are not contained in you dictionnary. This method return true if your wordList changed as a result of the call (after removing the non existing element), in other word, this method return false when all your wordList elements exists in you dictionnary.