在我的作业中,我需要得到这个输出:
输入一个词:house
你想要取代什么信?:e
你希望用什么信取代它? w ^
新词是housw。
_____________________________________________。
我得到了使用此代码的程序,但现在我需要设置while循环。这是我目前的代码。
String word ="&#34 ;; 扫描仪键盘=新扫描仪(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
keyboard.close();
System.out.println(word.replaceAll(readChar, changeChar));
System.out.println();
我现在需要让我的程序输出:
输入一个词:house
你要用什么字母取代?:a
没有内部。
你想替换什么信?:b
没有内部。
你想要取代什么信?:e
你希望用什么信取代它? w ^
新词是housw。
我的while循环如何描绘此输出?
答案 0 :(得分:3)
在您阅读了要替换的单词和字符(以及要替换它的字符)之后,您可以使用String类中的replace方法。
以下是一个示例用法(使变量名称适应您的代码)
word = word.replace(letterToReplace, replacementLetter);
所以例如
String word = "aba";
word = word.replace('a', 'c');
System.out.println(word); // Prints out 'cbc'
此处还有replace
方法的JavaDoc强制链接:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28char,%20char%29
答案 1 :(得分:1)
我希望你不介意硬解释,下面是你可以遵循的例子。
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
print.i(r);
答案 2 :(得分:1)
如果要替换所有字母,可以这样做(工作代码):
public static void main(String[] args) {
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
keyboard.close();
System.out.println(word.replace(readChar, changeChar));
}
答案 3 :(得分:1)
好的,这是实现编辑的第二部分问题的一种可能方式:
public static void main(String[] args) {
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
boolean done = false;
do{
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
if(word.contains(readChar)){
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
done = true;
keyboard.close();
System.out.println(word.replace(readChar, changeChar));
}
}
while(!done);
}
答案 4 :(得分:0)
这说明了你需要做什么。
import java.util.Scanner;
public class WordScrambler{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = keyboard.nextLine();
System.out.print("What letter do you want to replace?: ");
char letter = keyboard.next().charAt(0);
StringBuffer out = new StringBuffer(word);
System.out.print("With what letter do you wish to replace it? ");
char changeChar = keyboard.next().charAt(0);
for (int i=0; i<word.length(); ++i)
if(word.charAt(i) == changeChar)
out.setCharAt(i, changeChar);
System.out.println("The new word is "+out);
}
}