[英]arrays and for loops
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. 我是Java的新手,并且愿意发展我的技能,所以我写了这段代码,以学习Arrays,一位开发人员建议使用HashSet,我期待新的建议。
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". 我的问题:如果用户输入的单词不在MyArrayS中,该怎么办?我想检查一下并打印一条类似“ Word不存在”的语句。
I think that it might look like: 我认为它可能看起来像:
if(word!=MyArrayS)
{
System.out.println("Word does not exist");
}
Thanks 谢谢
您可以简单地使用.Contains(String)方法来确定单词是否包含在数组中。
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.