于是,我们的老师给我们提出了一个Java挑战,条件如下:
但限制是您不能使用函数split()、length()和toUpperCase()。
我的第一个想法是switch对每个字母都使用 and 大小写,但我想知道是否有更好的(读得更短、更聪明)替代方案:
public class program {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String text;
System.out.println("Type in:");
text = input.nextLine();
switch(text){
case "A":
System.out.println("a");
break;
case "b":
System.out.println("B");
break;
}
}
Run Code Online (Sandbox Code Playgroud)
你怎么认为?
是的,有更好的方法。首先,您需要通过执行以下操作来检查它是大写字母还是小写字母:
char c;
if(c >= 'a' && c <= 'z') {
c = c - 32
} else if(c >= 'A' && c <= 'Z') {
c = c + 32
}
Run Code Online (Sandbox Code Playgroud)
因为'A'的ASCII值为65,'B'为66等,'a'的ASCII值为97等。您需要更改每个字母表的 ASCII 值。我希望这有帮助。
| 归档时间: |
|
| 查看次数: |
9526 次 |
| 最近记录: |