CodeForces-131A-cAPS lOCK

A. cAPS lOCK
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

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.

Output

Print the result of the given word's processing.

Sample test(s)
input
cAPS
output
Caps
input
Lock
output
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);

	}

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章