问题描述
下面的Java程序应该以这种方式操纵用户输入的字符串,即用户将决定需要用另一个字符替换哪个字符,而应该替换字符串中的第一个字符。例如,如果用户输入字符串“ PUMP”并决定将“ P”替换为“ L”,则程序应输出以下结果:“ LUMP”(注意,只有第一个“ P”被替换为“ L” )
注意:您不能使用BREAK命令来停止循环。禁止。
我已经编写了以下程序,但我不能停止仅替换字符串的第一个字符:
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace the first character from the string entered by the user only
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
for(int index = 0;index < inString.length();index++) {
if(inString.charAt(index) == oldCharF){
outString = outString + newCharF;
}
else {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
我不断从上面的代码中得到这个结果:
Enter the string to be manipulated
PUMP
Enter the character to replace
P
Enter the new character
L
The new sentence is: LUML
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)