首页 > 解决方案 > 尝试制作 altcase。Char 被取消引用,我该如何解决这个问题?

问题描述

我正在尝试制作altcase。大多数程序都可以工作,除了我在 if 和 else 语句中将字符串一起添加的地方。(其中newstr = newstr ....)如果要运行,它应该输出'I HoPe aLtCaSe wOrKs'

public class tester {

    public static void main(String[] args) {

        System.out.println(altCase("i hope altcase works"));
    }
         public static String altCase(String text)
    {
        int COUNT = text.length();
        char c;
        int check = 0;
        String newstr = "";
        for (int i = 0; i < COUNT; i++)
        {
            c = text.charAt(i);
            if(check == 0) {
                c = c.toUpperCase();
                newstr = newstr + c;
                check++;
            }
            else {
                c = c.toLowerCase();
                newstr = newstr + c;
                check--;
            }
        }
        return newstr;
    }
}

标签: javachar

解决方案


如果您需要不使用toUpperCase()or的解决方案toLowerCase(),我建议您尝试一下。

public class Tester {

    public static void main(String[] args) {
        System.out.println(altCase("i hope altcase works"));
    }

    public static String altCase(String text) {
        char[] array = text.toCharArray();
        text ="";
        for (int i = 0; i < array.length; i++) {
            text += (i%2!=0)?array[i]:Tester.utilityToUpper(array[i]);
        }
        return text;
    }

    public static char utilityToUpper(char i){
        return (char) ((i!=' ')? (i - 32) : i);
    }

}

推荐阅读