2014-09-11 15 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