4.分析以下需求,并用代码实现:
(1)从键盘循环录入录入一个字符串,输入"end"表示结束
(2)将字符串中大写字母变成小写字母,小写字母变成大写字母,其它字符用"*"代替,并统计字母的个数
举例:
键盘录入:Hello12345World
输出结果:hELLO*****wORLD 总共10个字母
1 import java.util.Scanner; 2 3 public class Test_004 { 4 5 public static void main(String[] args) { 6 String a = input(); 7 //System.out.println(a); 8 char[] c = a.toCharArray(); 9 int count = 0; 10 for (int i = 0; i < c.length; i++) { 11 if (c[i]>'A' && c[i]<'Z') { 12 c[i]+=32; 13 count++; 14 }else if (c[i] >= 'a' && c[i]<='z') { 15 c[i]-=32; 16 count++; 17 }else{ 18 c[i] = '*'; 19 } 20 } 21 System.out.println("总共"+count+"个字母!"); 22 } 23 public static String input(){ 24 Scanner sca = new Scanner(System.in); 25 StringBuffer s = new StringBuffer(); 26 System.out.println("请输入一个字符串,完成后以(end)结尾!"); 27 while(true){ 28 String str = sca.next(); 29 if (str.endsWith("end")) { 30 System.out.println("输入结束!"); 31 break; 32 } 33 s.append(str); 34 } 35 return s.toString(); 36 } 37 }
运行结果:
1 请输入一个字符串,完成后以(end)结尾! 2 Hello12345World 3 end 4 输入结束! 5 hELLO*****wORLD 6 总共10个字母!