无法使用bool char方法将char转换为字符串

时间:2017-11-08 15:29:33

标签: java string casting char type-conversion

public class main {

    public static void main(String[] args) {
        isVowelTester();
    }

    public static boolean isVowel(char ch) {
        /*
        This method returns true if ch is a vowel 
        and returns false if ch is any other character. 
        Vowels are the letters a, e, i, o, and u.
         */
        ch = "cod";
        String str = Character.toString(ch);

        if (str.contains("a" + "A" + "e" + "E" + "i" + "I" + "o" + "O" + "u" + "U")) {
            return true;
        } else {
            return false;
        }

    }

    public static char isVowelTester() {
        return isVowelTester(System.out.println("Supplied word has vowels: " + isVowel()));
    }
}

它在ch =" cod&#34 ;;给我一个错误它无法转换。我查找了许多如何将它从char转换为字符串的示例,尽管它仍然给我一些与转换有关的错误。

有人可以给我一些转换建议吗?

4 个答案:

答案 0 :(得分:1)

public static boolean isVowel(char ch) {
    return "AaEeIiOoUu".contains(Character.toString(ch));
}

ch = 'y'; // possible
ch = "n"; // not possible a string cannot be assigned to a char variable

答案 1 :(得分:0)

String.valueOf(char)似乎是将char转换为String的最有效方法。

要查看所有方法,请查看链接6 ways to convert

答案 2 :(得分:0)

哦,我的......这是一团糟。首先看一下方法public static char isVowelTester()。你在这个方法中调用这个方法,我的意思是你正在使用递归。您最终将获得StackOverflowError,因为您只返回相同的方法作为回报,并且没有其他可能停止调用isVowelTester(),因此它将无休止地调用(直到溢出)。
你所能做的只是打印结果,无需退货:

public static void isVowelTester() {
    System.out.println("Supplied word has vowels: " + isVowel()));
}

但这还没有结束。在方法public static boolean isVowel(char ch)中,您有一个参数char ch。您必须为此方法提供一个参数。因此,必须更新我们之前的代码,以提供这一个参数。

public static void isVowelTester() {
    char ch = 'a';
    System.out.println("Supplied word has vowels: " + isVowel(ch)));
}

请注意,在分配char时我使用'',而不是“”。这是String和char之间的区别 最后,我们可以转到方法isVowel(char ch)。你不能将"cod"分配给char,因为这是3个字母和char,顾名思义,只有一个字符。你还使用引号,字符串中使用的是什么 你的if语句也是错的,因为你没有比较contains(...)参数中的每个字符,你要比较“AaEeIiOoUu”,因为+符号用于连接字符串。你是bassicaly连接元音,然后你比较一个字符,这永远不会是真的。更好的方法是颠倒你的陈述:

public static boolean isVowel(char ch) {
    String str = Character.toString(ch);

    if ("AaEeIiOoUu".contains(str)) {
        return true;
    } else {
        return false;
    }
}

这还没有结束。您可以对此进行优化,因为您基本上返回了if的结果。请注意,如果您的条件为真,则返回true,否则返回false。所以你可以写:return "AaEeIiOoUu".contains(str)。这就是你要做的一切。

答案 3 :(得分:0)

public class Main {

    public static void main(String[] args) {
        isVowelTester();
    }

    public static boolean isVowel(char ch) {
        /*
         * This method returns true if ch is a vowel and returns false if ch is
         * any other character. Vowels are the letters a, e, i, o, and u.
         */

        String str = new String(ch + "");
        String inMatchString  = "AaEeIiOoUu";

        if (inMatchString.contains(str)) {
            return true;
        } else {
            return false;
        }

    }

    public static void isVowelTester() {
        System.out.println("Supplied word has vowels: " + isVowel('a'));
    }
}

希望这会有所帮助。

相关问题