使用循环创建变量

时间:2017-10-05 21:32:03

标签: java string loops if-statement substring

我正在编写一个程序,该程序应该用另一个字母替换单个字母的所有实例。我对代码有一些限制,我只允许使用String方法.length,.substring,.indexOf和.equals。我可以用+而不是.concat连接东西。

我现在的问题是,当我将结果打印到程序时,答案必须包含在变量中。在我意识到这一点之前,我之前使用过此代码:

    if (userCommand.equalsIgnoreCase("replace all")) {
        System.out.println("Enter the character to replace");
        String replace = keyboard.nextLine();
        System.out.println("Enter the new character");
        String replaceWith = keyboard.nextLine();

        int count = 0;

        System.out.print("The new string is: ");
        while (lastCharacter >= 0) {
            char nextCharacter = userString.charAt(count);
            count++;
            String nextCharacterString = nextCharacter + "";
            if (nextCharacterString.equals(replace)) {
                nextCharacterString += replaceWith;
            }
            System.out.print(nextCharacterString);

            lastCharacter--;
        }
        System.out.println("");
    }

正如您所看到的,这会逐个打印每个角色到控制台,而不是作为稍后可以操作的变量。我现在正在使用的代码(它远没有工作)是:

    if (userCommand.equalsIgnoreCase("replace all")) {
        System.out.println("Enter the character to replace");
        String replaceString = keyboard.nextLine();
        char replace = replaceString.charAt(0);
        System.out.println("Enter the new character");
        String replaceWithString = keyboard.nextLine();
        char replaceWith = replaceWithString.charAt(0);
        String allLetters = "";
        int count = 0;
        int indexOfReplacement = 0;

        for (int i = 0; i < length; i++) {
            char nextCharacter = userString.charAt(count);
            count++;

            if (replace == nextCharacter) {
                indexOfReplacement = count;
                nextCharacter = replaceWith;
            }
        }
        String sub1 = userString.substring(0, indexOfReplacement);
        System.out.println(sub1);
    }

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

这是我写的一个小片段。我对变量的内容做了一些假设,以使其能够运行,但它有效,用from functools import partial tk.Button(transport_frame, text=car.range, command= partial(change_range, car)).grid(row=1, column=car_column) 替换replace的所有实例:

replaceWith

答案 1 :(得分:0)

您可以使用arraylist

ArrayList<String> list=new ArrayList<String>();
while(lastCharacter >= 0)
              {
                  char nextCharacter = userString.charAt(count);
                  count ++;
                  String nextCharacterString = nextCharacter + "";
                  if (nextCharacterString.equals(replace))
                  {
                      nextCharacterString += replaceWith;  
                  }
                  System.out.print(nextCharacterString);
                  list.add(nextCharacterString);
                  lastCharacter --;
              }

所以你以后可以操纵它