jeudi 5 octobre 2017

Creating a Variable Using a Loop

I'm writing a program that's supposed to replace all of the instances of a single letter with another letter. I have some restrictions on the code though, I'm only allowed to use the String methods .length, .substring, .indexOf, and .equals. I can concatenate things using + instead of .concat.

My problem right now is, when I'm printing my results to the program, the answer has to be contained in a variable. I was previously using this code before I realized this:

 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("");

As you can see, this prints each character to the console one by one, instead of as a variable that can be manipulated later. The code I'm using right now (it is nowhere near working) is:

      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);
                }

Any help would be very much appreciated.

Aucun commentaire:

Enregistrer un commentaire