...
import java.util.Scanner; public class Test { /** * 測試數據 * * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); System.out.println(ExchangeStringA(s)); System.out.println(ExchangeStringB(s)); } /** * 方式一 * * @param s * @return */ public static String ExchangeStringA(String s) { StringBuffer result = new StringBuffer(); String lowerString = s.toLowerCase(); //這兩步 String upString = s.toUpperCase(); //是關鍵 for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == lowerString.charAt(i)) { result.append(upString.charAt(i)); } else { result.append(lowerString.charAt(i)); } } return result.toString(); } /** * 方式二 以字母的ascii碼來操作 大小寫之間相差32 * a-z:97-122 * A-Z:65-90 * @param s * @return */ public static String ExchangeStringB(String s) { char c[] = s.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] >= 65 && c[i] <= 90) { c[i] = (char) (c[i] + 32); } else { c[i] = (char) (c[i] - 32); } } return String.valueOf(c); } }