我正在尝试创建一个随机生成字母表中的字母的功能,用户需要键入“A”代表元音字母,“B”代表辅音字母。然后,系统将通过搜索阵列中的字母来检查答案是否正确。
但是,我收到了这个错误:
无法找到符号
符号:方法indexOf(char)
请检查下面的代码。
public static void Exam_LetterType() throws Exception
{
BufferedReader temp = new BufferedReader(new InputStreamReader(System.in));
String Alphabet[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String Vowel[]={"a","e","i","o","u"};
String Consonant[]={"b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"};
Random x = new Random();
int Index;
String Answer;
int CorrectAnswer = 0;
for(int i=1;i<=20;i++)
{
Index = x.nextInt(26);
System.out.println ("\n A) VOWEL LETTER B) CONSONANT LETTER");
System.out.print(" Letter" + "'" + Alphabet[Index] + "'" + " is a: ");
String Question = Alphabet[Index];
Answer = temp.readLine();
if(Vowel.indexOf(Question).equals(-1))
if(Answer.equals("B"))
{
CorrectAnswer = CorrectAnswer + 1;
}
else if(Consonant.indexOf(Question).equals(-1))
{
if(Answer.equals("A"))
{
CorrectAnswer = CorrectAnswer + 1;
}
else
{
CorrectAnswer = CorrectAnswer + 0;
}
}
}
}
期待您的回复。谢谢!
答案 0 :(得分:2)
确保对数组进行排序并使用Arrays.binarySearch
答案 1 :(得分:1)
首先,Array class中没有indexOf
方法。
甚至在这里
if(Vowel.indexOf(Question).equals(-1))
您无法将整数值与使用equals
==
进行比较
该行应为
if(// check here that weather the value **i** lesser than the length of array)
if(Vowel[i].indexOf(Question)== -1))
那解决了,
由于您要进行多次比较,只需编写一个Util方法,检查字符串是否在array
中。
public boolean arrayContainsString(String[] arrayToLookUp, String str){
boolean contains = false;
for (String item : arrayToLookUp) {
if (str.equalsIgnoreCase(item)) { //case or not
contains = true;
break; // No need to look further.
}
}
return contains;
}
然后您可以使用该方法,只需
if(arrayContainsString(Vowel, Question)){
//proceed furthur
}
作为旁注:请关注java naming conventions。varaibles名称以小写字母开头。
答案 2 :(得分:0)
试
if(Arrays.asList(Vowel).contains(Question))
答案 3 :(得分:0)
尝试这个..
您需要更改下面显示的两个条件
Vowel[i].indexOf(Question) == -1
和
Consonant[i].indexOf(Question) == -1
您可以在下面找到完整的编辑代码:
public static void Exam_LetterType() throws Exception
{
BufferedReader temp = new BufferedReader(new InputStreamReader(System.in));
String Alphabet[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String Vowel[]={"a","e","i","o","u"};
String Consonant[]={"b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"};
Random x = new Random();
int Index;
String Answer;
int CorrectAnswer = 0;
for(int i=1;i<=20;i++)
{
Index = x.nextInt(26);
System.out.println ("\n A) VOWEL LETTER B) CONSONANT LETTER");
System.out.print(" Letter" + "'" + Alphabet[Index] + "'" + " is a: ");
String Question = Alphabet[Index];
Answer = temp.readLine();
if(Vowel[i].indexOf(Question) == -1)
if(Answer.equals("B"))
{
CorrectAnswer = CorrectAnswer + 1;
}
else if(Consonant[i].indexOf(Question) == -1)
{
if(Answer.equals("A"))
{
CorrectAnswer = CorrectAnswer + 1;
}
else
{
CorrectAnswer = CorrectAnswer + 0;
}
}
}}