【发布时间】:2020-10-15 11:48:51
【问题描述】:
下面的 Java 程序应该以这样一种方式操作用户输入的字符串,即用户将决定哪个字符需要替换为另一个字符,并且只替换字符串中的最后一个字符。例如,如果用户输入字符串“OYOVESTER”并决定将“O”替换为“L”,程序应输出以下结果:“OYLVESTER”(注意只有最后一个“O”被替换为“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 Last
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);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
我不断收到以下不正确的输出:
输入要操作的字符串
奥维斯特
输入要替换的字符
哦
输入新字符
L
新句子是:LRETSEVOY
【问题讨论】:
-
由于您在重建字符串时从头到尾迭代字符串,因此您还必须考虑这一点并切换字符串附加的顺序,使其为
outputString = appendString + outputString。您在三个地方之一正确地做到了这一点,但在另外两个地方却没有。循环内的字符串应始终采用outString = x + outString的形式,其中 outString 是追加时的第二个参数。