Steve
Lv 6
Steve asked in 電腦與網際網路程式設計 · 1 decade ago

JAVA大小寫的轉換

題目:

  設計一個Java程式,將一組字串中的大寫字母變成小寫字母,並將小寫字母變成大寫字母,再將結果輸出:

設定的字串:Hello Java

輸出的字串:hELLO jAVA

以下是我寫的程式不知哪有錯,無法換大小寫?

public class Test01{

public static void main(String[] args){

char[] chr = {'H','e','l','l','o',' ','J','a','v','a'};

for(int i=0; i<chr.length; i++){

if(Character.isLetter(chr[i])){

if(Character.isUpperCase(chr[i])){

Character.toLowerCase(chr[i]);

}else{

Character.toUpperCase(chr[i]);

}

}

System.out.print(chr[i]);

}

System.out.println();

}

}

2 Answers

Rating
  • Aiolus
    Lv 5
    1 decade ago
    Favorite Answer

    雖然有更簡便的寫法.. 不過就基於你的程式改好了

    public class Test01{

    public static void main(String[] args){

    char[] chr = "Hello Java".toCharArray();

    for(int i=0; i<chr.length; i++){

    if(Character.isLetter(chr[i])){

    if(Character.isUpperCase(chr[i])){

    //你原程式沒有賦值回去,toLowerCase是傳回新的Char而不是改掉舊的Char

    chr[i]=Character.toLowerCase(chr[i]);

    }else{

    chr[i]=Character.toUpperCase(chr[i]);

    }

    }

    System.out.print(chr[i]);

    }

    System.out.println();

    }

    }

  • 1 decade ago

    請參考我的做法

    public class Y8753 { public static void main(String[] args) { String s = "Hello Java"; StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= 97 && c <= 122) c -= 32; else if (c >= 65 && c <= 90) c += 32; sb.append(c); } System.out.println("設定的字串:" + s); System.out.println("輸出的字串:" + sb.toString()); }}

Still have questions? Get your answers by asking now.