我不知道为什么我会收到这个错误。我认为一般的代码是可以的,虽然我确信有一个更短的方法,然后使用所有其他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);
}
}
答案 0 :(得分:4)
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;
}
答案 1 :(得分:1)
String lineOne, R2D2 = "";
R2D2是一个字符串,您正在与字符if (R2D2== 'a'|| R2D2=='A')
试试这个
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++;
}
一方面不是,您应该使用.equals()
代替==
答案 2 :(得分:0)
如果你想修复long 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;
}
答案 3 :(得分:-2)
R2D2
的类型为String,而单个引号围绕一个字符(如'a'
中所示)使其成为字符文字。字符串不能分配或与字符比较。这就是原因。
代码中存在两种问题。
1. `R2D2= lineOne.charAt(i); // a character being assigned to a String variable`
解决方案:R2D2 = Character.toString(lineOne.charAt(i));
2. `if (R2D2== 'a'|| R2D2=='A')` //strings being compared with char literals.
解决方案:if (R2D2.equals("a")|| R2D2.equals("A"))
仅供参考,为了改善维护,您也可以这样做。
if(R2D2.equalsIgnoreCase('a'))