本题要求编写程序,对一个以“#”结束的字符串,将其小写字母全部转换成大写字母,把大写字母全部转换成小写字母,其他字符不变输出。
输入格式:
输入为一个以“#”结束的字符串(不超过30个字符)。
输出格式:
在一行中输出大小写转换后的结果字符串。
输入样例:
Hello World! 123#
输出样例:
hELLO wORLD! 123
代码部分:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try (// TODO Auto-generated method stub
Scanner in = new Scanner(System.in)) {
int i;
String str = new String();
str = in.nextLine();
for(i=0;i<str.length()-1;i++)
{
if(str.charAt(i)>='a' && str.charAt(i)<='z')
{
System.out.print((char)(str.charAt(i) - 'a' + 'A'));
}
else if(str.charAt(i)>='A' && str.charAt(i)<='Z')
{
System.out.print((char)(str.charAt(i) -'A' + 'a'));
}
else
System.out.print((char)str.charAt(i));
}
in.close();
}
}
}
可比较ASCII码区间判断大小写
ASCII码规则:大写在前小写在后,数字在前字母在后。
48 - 57:数字0 - 9
65 - 90:字母A - Z
97 - 122:字母a - z
注:输出时需利用强制类型转换,否则输出的是ASCII码。
小技巧( 请教大佬的):当题目要求输入以xxx字符为结束的字符串,可 ① String str = new String ( ) ; ② 循环条件:i < str.length ( ) - 1 。避免使用单个字符串进行循环输入,如 while ( true ) 等循环。
java刚入门小白,如有错误或优化欢迎大佬们的指点!