2014-09-11 50 views
0

我試圖在Java中創建用戶創建(輸入)一個短語,然後選擇(輸入)一個字符的代碼。 從那裏我想採取用戶輸入並將他們選中的字符替換爲他們創建的短語中的X.我不完全知道如何創建這個,我知道我想使用掃描儀,然後我不知道是否必須創建一個新的字符串或使用突變方法。它假設看起來像這樣運行時:在Java中,當用戶輸入要替換的短語和字符時,如何替換字符?

  • 輸入短語:披薩好
  • 輸入字符:
  • Pixxa好

我是相當新的Java和這什麼到目前爲止,我已經試過

這裏是我的代碼:

import java.util.Scanner; 
public class ModifyStrings 
{ 
public static void main (String[] args) 
{ 
String enterPhrase; 
    String enterCharacter; 

    //Scanner 
    Scanner scan2 = new Scanner (System.in); 

    //Print out that the user will see and type in 
    System.out.println("Enter a phrase or sentence: "); 
      enterPhrase = scan.nextLine(); 

    //Second print out that the user will enter in for a character to change 
    System.out.println("Enter Character: "); 
    enterCharacter = scan.nextLine(); 

    //mutation 
      ? 

    //Character changes that letter into x 
    System.out.println("New phrase: "+ enterPhrase); 
    } 
} 

謝謝!

回答

2

這很簡單,可以通過使用String方法replaceAll()來完成。嘗試下面的代碼將爲你工作。

import java.util.Scanner; 

public class ModifyStrings { 

    public static void main (String[] args) { 

     String enterPhrase; 
     String enterCharacter; 

     //Scanner 
     Scanner scan = new Scanner (System.in); 

     //Print out that the user will see and type in 
     System.out.println("Enter a phrase or sentence: "); 
       enterPhrase = scan.nextLine(); 

     //Second print out that the user will enter in for a character to change 
     System.out.println("Enter Character: "); 

     // This line of code firstly get the string truncate white spaces and then get the first character not all 
     enterCharacter = scan.nextLine().trim().substring(0, 1); 

     //Mutation code replace x with your desired character do you want to replaces 
     enterPhrase = enterPhrase.replaceAll(enterCharacter, "x"); 


     //Character changes that letter into x 
     System.out.println("New phrase: "+ enterPhrase); 
} 
} 
+0

非常感謝!如果用戶輸入了他們所做短語中沒有使用過的字符,我將如何處理錯誤信息?
例如,
如果他們在J和J中未使用它將打印
「錯誤:字符不在短語中」。
這是一個布爾值,還是不同類型的打印輸出?我很抱歉這麼問。 – 2014-09-12 09:27:46

+0

@Not_a_bandwagoner你可以在從用戶獲取輸入字符後使用包含字符串的「(」)方法,並檢查在給定字符串中找到的將返回布爾值的字符。請檢查此解決方案下面的代碼行。如果(enterPhrase.contains(enterCharacter)){\t \t //您想要替換x所需字符的突變代碼是否需要替換\t \t \t enterPhrase = enterPhrase.replaceAll(enterCharacter,「x」); \t \t \t //將字母改爲x的字符\t \t \t System.out.println(「New phrase:」+ enterPhrase); \t \t} else { \t //打印錯誤信息你想要什麼 } – 2014-09-13 06:21:15