Reputation: 4727
Sorry, silly question here, I have googled it but anything I search for seems to be returning methods of using binary search etc., but what I need is actually much simpler.
I have an array of languages. I am creating a scanner, asking for input. Trying to make it so that if the language input by the user isn't in the array, it displays an error and asks again. Should be simple, I have just drawn a blank.
Can anyone help please ? Here is what I have so far !
Scanner scan = new Scanner(System.in);
language = scan.next();
while( language NOT IN ARRAY languages) {
System.out.print("error!");
language = scan.next();
}
Upvotes: 2
Views: 424
Reputation: 103135
You can do this is you really need to use an array:
Arrays.sort(languages);
Scanner scan = new Scanner(System.in);
language = scan.next();
while( Arrays.binarySearch(languages, language) < 0) {
System.out.print("error!");
language = scan.next();
}
Upvotes: 1
Reputation: 138874
I understand your question better now. You should use a Set
for sure. But you will want to use the contains()
method of the set to check if the language exists.
Scanner scan = new Scanner(System.in);
language = scan.next();
while(!set.contains(language)) {
System.out.print("error!");
language = scan.next();
}
Old answer, still relevant info though:
What yo want to use is a Set
collection type. A set does not allow duplicate entries.
From the Javadocs:
A collection that contains no duplicate elements.
Set<String> set = new HashSet<String>();
// will not add another entry if set contains language already
set.add(language);
Also, if you want to know if the value was rejected or not, you can use the return type of the add() method. It returns true if the item did not exist, and false otherwise.
Upvotes: 4
Reputation: 2155
There are two things you can do:
Either iterate through the array and compare the contents on each element to what you're trying to see if it's there every time you add a language.
OR
Use a LinkedList or some other kind of Java Structure that has a .contains()
method, this will, in a way, do something similar to what I mentioned for the Array.
Upvotes: 0
Reputation: 32923
You can do something like:
public static boolean contains(String language, String[] lang_array) {
for (int i = 0; i < lang_array.length; i++) {
if (lang_array[i].equals(language))
return true;
}
return false;
}
public static void main(String[] args) {
String[] lang_array = {"Java", "Python", "Ruby"};
Scanner scan = new Scanner(System.in);
String language = scan.next();
while(!contains(language, lang_array)) {
System.out.print("error!");
language = scan.next();
}
}
Upvotes: 1