我不知道为什么我会犯这个错误。我认为代码在一般情况下是可以的,尽管我确信有一种比使用其他所有ifs更短的方法。问题是它说不兼容类型,我真的不知道如何解决这个问题。任何帮助都将不胜感激。
import java.util.Scanner;
public class MissionImpossible
{
public static void main(String [] args){
String lineOne, R2D2 = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a word so I can see how many vowels it has.");
int count = 0;
lineOne = in.nextLine();
int word = lineOne.length();
for (int i = word -1; i>= 0; i--)
{
R2D2= lineOne.charAt(i);
if (R2D2== 'a'|| R2D2=='A')
count++;
else if (R2D2=='e'||R2D2=='E')
count++;
else if (R2D2=='o'|| R2D2=='O')
count++;
else if (R2D2=='u'||R2D2=='U')
count++;
else if (R2D2=='y'||R2D2=='Y')
count++;
}
System.out.println(count);
}
}发布于 2013-11-17 05:48:33
char不是String。声明R2D2为char
char R2D2 = '';要检查元音,请创建如下所示的方法,并在for循环和count中重用该方法:
static boolean isVowel(char ch) {
ch = Character.toLowerCase(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
return true;
}
return false;
}发布于 2013-11-17 05:49:49
String lineOne, R2D2 = "";R2D2是一个字符串,您正在与char if (R2D2== 'a'|| R2D2=='A')进行比较。
尝尝这个
对于(int i= word -1;i>= 0;i-){ R2D2= lineOne.charAt(i);
if (R2D2=="a"|| R2D2=="A")
count++;
else if (R2D2=="e"||R2D2=="E")
count++;
else if (R2D2=="o"|| R2D2=="O")
count++;
else if (R2D2=="u"||R2D2=="U")
count++;
else if (R2D2=="y"||R2D2=="Y")
count++;
}一方面不是,您应该使用.equals()而不是==进行比较。
发布于 2013-11-17 05:52:28
如果您想要修复长If链,您可以这样做:
if (anyOf(R2D2, "AaEeIiOoUuYy".toCharArray())后来又有:
private static boolean anyOf(char in, char[] items) {
for (int i = 0; i < items.length; i++) {
if (in == items[i])
return true;
}
return false;
}https://stackoverflow.com/questions/20027673
复制相似问题