本帖最後由 李泳霖 於 2022-6-11 18:56 編輯
題目說明:
請將檔案另存成JPA04.java,並編譯為JPA04.class
設計說明:
1.請使用遞迴設計一個類別方法,此方法能夠將一個字串內的某個字元換成另一個字元。例如輸入字串[windows],將字串中的w值替換成g值,輸出字串為[gindogs]。
2.程式執行時,顯示[Input a string: ]要求輸入字串,接續顯示[Input a character: ] 要求輸入[被替換]的字元,最後顯示[Input another character: ]要求輸入替換字元。
3.請利用replace()函數進行字串替換,顯示如執行結果參考畫面。
replace("windows","w","g")
="g"+replace("indows","w","g")
="g"+"i"+replace("ndows","w","g")
="g"+"i"+"n"+replace("dows","w","g")
="g"+"i"+"n"+"d"+replace("ows","w","g")
="g"+"i"+"n"+"d"+"o"+replace("ws","w","g")
="g"+"i"+"n"+"d"+"o"+"g"+replace("s","w","g")
="g"+"i"+"n"+"d"+"o"+"g"+"s"+replace("","w","g")
="g"+"i"+"n"+"d"+"o"+"g"+"s"+""
=gindogs- import java.util.Scanner;
- public class JPD04 {
- static Scanner keyboard = new Scanner(System.in);
- public static void main(String args[]) {
- String s, c1, c2;
- System.out.print("Input a string: ");
- s = keyboard.nextLine();
- System.out.print("Input a character: ");
- c1 = keyboard.nextLine();
- System.out.print("Input another character: ");
- c2 = keyboard.nextLine();
- System.out.printf("%s\n", replace(s, c1, c2));
- }
-
- ...
- }
複製代碼 |