1

I am learning about arrays and I did quiet a few experiments, most of them went well, however now I'm stuck. What I want to archive is, find if an specific value (String, int or whatever), exists inside an Array and if it does, use that value for something i.e the code below which I basically count how many times that value was present inside the array:

package arraysOnly;
import java.util.*;
public class ArrayContainsString
{
    public static void main(String[]args)
        {       
            Scanner sc = new Scanner(System.in);
            int arraySize = 0;
            int wordCount = 0;

            System.out.println("How many words are you gonna type?: ");
            arraySize = sc.nextInt();

            String[] words = new String[arraySize];     // Simple array, the size of which will be decided from the user-input

            for(int count = 0; count < arraySize; count++)
            {
                System.out.println("Enter your " + (count+1) + ": ");
                words[count] = sc.next();
            }

            //Basically this is the part I'm having troubles
             if(in_array("ubt", $words)
            {
                 wordCount++;
            }
        }
}

I know about this,

if(Arrays.asList(words).contains("ubt"));

which basically converts the array into an List / ArrayList or whatever, however I want to treat this as an array only if possible.

3 Answers 3

2

An array is the wrong data structure; a Set is the weapon of choice:

Set<String> words = new HashSet<>()
for (int count = 0; count < arraySize; count++) {
    System.out.println("Enter your " + (count+1) + ": ");
    words.add(sc.next());
}

if (words.contains("ubt"))
    wordCount++;
}

The contains() method of a HashSet completes in constant time not matter how large the set is. Although performance is irrelevant for small input sizes like this usage, it's good to get in the habit of choosing the right tools for the job. It also makes your code cleaner.

Generally speaking, don't use arrays unless you absolutely have to; they are only rarely used in commercial code.

Sign up to request clarification or add additional context in comments.

3 Comments

I know it might not be the best, I mean ArrayList are just perfect for almost any occasion however, I gotta learn all the corners of Java including Arrays and whatever they can and cannot do. I'm learning for my college Exam.
@Bohemian could you elaborate on "how arrays are rarely used in commercial code", why is this? do you have an article I can look at to learn more?
@coderrick arrays have no "convenience" about them - you must micro-manage them. Collections on the other hand have lots of instance methods and utility method support, and they are just easier to use (not the least of which is they grow in size automatically on demand), They are virtually as fast as arrays (being backed by them), and let you get on with writing code that matters.
2

The simple solution

public static boolean contains(String toFind, String[] strings) {
    for (String str : strings) {
        if (str.equals(toFind)) return true;
    }
    return false;
}

EDIT: To increase it after the user inputs a word, use this in the loop:

System.out.println("Enter your " + (count+1) + ": ");
words[count] = sc.next();
if (words[count].equals("ubt")) wordCount++;

3 Comments

I'm confused here, how do I add this to my code to increase the value of wordCount, everytime the specific word is typed?
Sorry, I thought you were asking for another thing xD. After words[count] = sc.next();, add 'if (words[count].equals("ubt")) wordCount++;
hat scans the input however, I want to scan the array itself, after all the wanted words are typed. Which means all the input will be done and the array will be filled with elements, after that I want to scan it and find if the specific value exists, I tried this however (as suggested from @SURESH ATTA. And I think this might be exactly what I was looking for. Thanks anyways, I'll write down your code down for future personal reference.
1

You can just iterate over array

for (String str : array){
  if(str.equals("ubt")){    
   wordCount++;
 }    
}

Edit:

It's just equivalent to a normal for loop

for(int i=0; i<array.length; i++) {
    if(array[i].equals("ubt")){    
       wordCount++;
     } 
} 

6 Comments

Aside from the typo, this doesn't have the same behavior as the OP had in their current solution.
Is the above code is not replacement for if(Arrays.asList(words).contains("ubt")); ?
No, it has different behavior for multiple matches within the array.
What's the ' String str : array ' part do? I just want to make sure I'm not "cheating" by converting the array into an ArrayList or whatever else.
Alright mate, thank you very much. This was exactly what I was looking for. Much appreciated <3
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.