wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentally switched on, if:
- either it only contains uppercase letters;
- or all letters except for the first one are uppercase.
In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.
Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.
The first line of the input data contains a word consisting of uppercase and lowercase Latin letters. The word's length is from 1 to 100 characters, inclusive.
Print the result of the given word's processing.
cAPS
Caps
Lock
Lock
首先考虑到了一种方法,但是较为的复杂,主要在比较字符串是否均为小写字母够成时,较为繁琐,体现在两个地方:1、运用循环思想,判断单个字符是否为小写。2、因为需要运用单个字符比较,只能使用StringBuffer类,需要进行转换。(toLowerCase()函数只有在String中才有)
import java.util.*;
public class CapsLock {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
String tempString = inScanner.nextLine();
StringBuffer sBuffer = new StringBuffer(tempString);
StringBuffer subBuffer = new StringBuffer("");
int x = 0;// ini
boolean isAllUpper = true;
char start = sBuffer.charAt(0);
if (sBuffer.length() > 1)
subBuffer = new StringBuffer(sBuffer.substring(1));
while (x < subBuffer.length()) {
if (Character.isLowerCase(subBuffer.charAt(x))) {
isAllUpper = false;
break;
}
x++;
}
if (isAllUpper) {
if (Character.isLowerCase(start))
System.out.print(Character.toUpperCase(start));
else {
System.out.print(Character.toLowerCase(start));
}
if (sBuffer.length() > 1) {
System.out.println(subBuffer.toString().toLowerCase());
}
} else
System.out.println(sBuffer);
}
}
后来经过分析,有以下几点改进:
import java.util.Scanner;
public class P131A {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String w = s.next();
if (w.substring(1).toUpperCase().equals(w.substring(1)))//判断是否均为大写
System.out.println(
(Character.isLowerCase(w.charAt(0)) ?//字符串输出前的修正
Character.toUpperCase(w.charAt(0)) :
Character.toLowerCase(w.charAt(0)))
+ w.substring(1).toLowerCase());
else System.out.println(w);
}
}