Reputation: 29
I wrote this code. I am new to Java and willing to develop my skills,so I wrote this code,in order to learn Arrays,one developer suggested HashSet,I am looking forward for new suggestions.
import java.io.*;
public class dictionary
{
public static void main(String args[])
{
String[] MyArrayE=new String[5];
String[] MyArrayS=new String[5];
MyArrayE[0]="Language";
MyArrayE[1]="Computer";
MyArrayE[2]="Engineer";
MyArrayE[3]="Home";
MyArrayE[4]="Table";
MyArrayS[0]="Lingua";
MyArrayS[1]="Computador";
MyArrayS[2]="Ing.";
MyArrayS[3]="Casa";
MyArrayS[4]="Mesa";
System.out.println("Please enter a word");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String word= null;
try {
word= br.readLine();
} catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Your word is " + word);
for(int i=0; i<MyArrayE.length; i++)
{
if(word.equals(MyArrayS[i]))
{
System.out.println(MyArrayE[i]);
}
}
}
}
My Question: What about if the user inputs a word not in MyArrayS, I want to check that and print a statement like "Word does not exist".
I think that it might look like:
if(word!=MyArrayS)
{
System.out.println("Word does not exist");
}
Thanks
Upvotes: 0
Views: 295
Reputation: 3334
You can simply use the .Contains(String) method to determine whether the word is contained within the array.
Upvotes: 1
Reputation: 5610
You have to check every element of the array to see that it's not there. So your code would actually look like:
int c;
boolean found = false;
for(c = 0;c < MyArrayS.length;c++) {
if(MyArrayS.compareTo(word) == 0) {
found = true;
}
}
if(!found) {
System.out.println("Word does not exist");
}
Upvotes: 0