java - 尝试制作 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;
}
}
解决方案
如果您需要不使用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);
}
}
推荐阅读
- c# - 如何在没有进程锁定的情况下一次处理一堆文件
- c - 从 Fortran 调用 C dll
- dart - 如何使用 bloc 并在 dart 中手动侦听 bloc.state 而不是通过 Flutter 或 AngularDart 的 bloc 管道?
- android - Android 解密后如何播放 DRM 内容?
- python - Pandas 数据框将每个组除以一个函数中的最大值
- html - 如何设置导航菜单项之间的不同间距?
- java - TestNG 如何在每个测试用例中使用 DataProvider 之前重新初始化它?
- php - 如何在两个表中查找具有特定积分且未订阅记录的用户
- c - 十六进制转换后如何将位移到左
- keras - 如何解决问题:“'Tensor'对象不支持项目分配”