如何使用for循环将以下程序解析为适当的输出?

问题描述

以下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);
        

    }

}

我不断收到以下不正确的输出

输入要操作的字符串

OYOVESTER

输入要替换的字符

O

输入新字符

L

新句子是:LRETSEVOY

解决方法

有许多更简单的方法可以满足您的要求,但我希望您必须通过循环(不间断)来证明这一点

然后您可以使用类似这样的东西:

boolean skip = false;

for (int index = inString.length() - 1; index >= 0; index--) {
  if (!skip && inString.charAt(index) == oldCharF) {
    outString = newCharF + outString;
    skip = true;
  }
  else {
    outString = inString.charAt(index) + outString;
  }
}

PS:不建议在循环内部使用字符串连接,因为 每个String串联都会复制整个String,通常最好 将其替换为对StringBuilder.append()StringBuffer.append()

的显式调用 ,

没有break命令似乎很奇怪。您可以使用布尔值和其他方法来在需要时中断循环。为什么不这样做呢?

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the string to be manipulated");
    String word = keyboard.nextLine();

    //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 index = word.lastIndexOf(oldCharF);
    if(index > 1){
        word = word.substring(0,index) + newCharF + word.substring(index+1);
    }

    System.out.println("The new sentence is: " + word);
}