0

I am new to programming and this is my first semester in programming introduction class. I am working on this project and came across few problems. I am only limited to use string methods like (length, concat, +, charAt, substring, and equals (or equalsIgnoreCase)) and I am prohibited to use StringBuilder, indexOf, Arrays. Any help would be very much appreciated...as I am just lost.

Here is my code that manipulates an entered string in various ways. I have made it to loop the whole process until the user enters "quit". When looping through consecutively, the resulting string is doubled. It seems like the result from the first loop is printed altogether with strings modified in the next loops. The string does not need to be cleared and reset but, it has to be kept modified by user until quitted.

GOOD EXAMPLE: 1st loop:"esrever"(word reverse is reversed) and 2nd loop: "srvr" (all char e is removed) and so on.

There are two problems that I am facing:

  1. when the do-while loop is repeated, the command prompt System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove, quit)"); sometimes prints double. can you tell me what is wrong with what I am doing?

  2. when the do-while loop is repeated, the new result is concatenated to the result right before. for example, when I reverse my string "reverse", I get "esrever" and when the do while produces second result of reverse, the newly reversed string is concatenated before "esrever" resulting in, "esreveresrever"

I googled and found out that clearing my scanner would solve, so I added keyboard.nextLine(); like this:

do { System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove, quit)"); command = keyboard.nextLine(); keyboard.nextLine();

but this did not solve my problem. Instead, it was creating an unnecessary prompt to press enter to proceed. What is wrong with my method?

Attempted to solve

            do {
    System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove, quit)");
    command = keyboard.nextLine();
    }while(!command.equalsIgnoreCase("quit"));

Attempted to solve by adding nextLine

            do {
    System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove, quit)");
    command = keyboard.nextLine();
    keyboard.nextLine();
    }while(!command.equalsIgnoreCase("quit"));

This is my whole code

import java.util.Scanner;

public class StringFun {

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);

    String originalString;
    String modifiedString="";
    String command="";
    char enterReplaceChar;
    char enterNewChar;
    char enterRemoveChar;
    int selectedCharToRemove=0;
    int whichToRemove;
    int stopOrGo=0;
    
    System.out.println("Enter the string to be manupulated");
    originalString = keyboard.nextLine();
    
    do {
    System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove, quit)");
    command = keyboard.nextLine();
    
    //reverse command
    if (command.equalsIgnoreCase("reverse")) {
        for (int i = originalString.length()-1; i>=0; i--) {
            modifiedString = modifiedString + originalString.charAt(i);}
        System.out.println("The new sentence is: " + modifiedString);}
        
    //replace first command
    
    else if (command.equalsIgnoreCase("replace first")) {
        System.out.println("Enter the character to replace");
        enterReplaceChar = keyboard.next().charAt(0);
        System.out.println("Enter the new character");
        enterNewChar = keyboard.next().charAt(0);
        for(int i=0; originalString.length() > i  ;i++) {
            if (stopOrGo < 1)
                if (originalString.charAt(i)== enterReplaceChar) {
                    stopOrGo++;
                    modifiedString = modifiedString + enterNewChar;}
                else {modifiedString = modifiedString + originalString.charAt(i);}
            else {modifiedString = modifiedString + originalString.charAt(i);}}
        if (modifiedString.equals(originalString)) {
            System.out.println("The letter was not found in the word");
        }else {
            System.out.println("The new sentence is:"+ modifiedString);}
        }

                        
    else if (command.equalsIgnoreCase("replace last")) {
        System.out.println("Enter the character to replace");
        enterReplaceChar = keyboard.next().charAt(0);
        System.out.println("Enter the new character");
        enterNewChar = keyboard.next().charAt(0);
        for(int i=originalString.length()-1; i >= 0  ;i--) {
                if (stopOrGo < 1)
                    if (originalString.charAt(i)== enterReplaceChar) {
                        stopOrGo++;
                        modifiedString =  enterNewChar + modifiedString;}
                    else {modifiedString =  originalString.charAt(i) + modifiedString;}
                else {modifiedString = originalString.charAt(i) + modifiedString;}}
        if (modifiedString.equals(originalString)) {
            System.out.println("The letter was not found in the word");
        }else {
            System.out.println("The new sentence is:"+ modifiedString);}
        }
    
    //remove all loop
    
    else if (command.equalsIgnoreCase("remove all")) {
        System.out.println("Enter the character to remove");
        enterRemoveChar = keyboard.next().charAt(0);
        for(int i=0; originalString.length() > i  ;i++) 
            if (originalString.charAt(i)== enterRemoveChar) {
                modifiedString = modifiedString + originalString.substring(i,i);}
            else {modifiedString = modifiedString + originalString.substring(i,i+1);}
        if (modifiedString.equals(originalString)) {
            System.out.println("Error: the letter you are trying to remove does not exist");
        }else {
            System.out.println("The new sentence is:"+ modifiedString);}
        }
    
    //remove selected loop
                
    else if (command.equalsIgnoreCase("remove")) {
        System.out.println("Enter the character to remove");
        enterRemoveChar = keyboard.next().charAt(0);
        System.out.println("Enter the " + enterRemoveChar + " you would like to remove (Not the index-1=1st, 2=2nd, etc.):");
        whichToRemove = keyboard.nextInt();
        for(int i=0; originalString.length() > i  ;i++) {
            if (originalString.charAt(i)==enterRemoveChar) {
                selectedCharToRemove++;
                if (selectedCharToRemove==whichToRemove) {
                    modifiedString = modifiedString + originalString.substring(i,i);
                }
                else  {modifiedString = modifiedString + originalString.substring(i,i+1);}}
            else {modifiedString = modifiedString + originalString.substring(i,i+1);}}
        if (modifiedString.equals(originalString) || (whichToRemove > selectedCharToRemove)) {
            System.out.println("Error: the letter you are trying to remove does not exist");
        }else {
            System.out.println("The new sentence is:"+ modifiedString);}
        }

    }while(!command.equalsIgnoreCase("quit"));
    
    System.out.println("...Execution Ends..."); 
    keyboard.close();
    System.exit(0);
    
    

} }

Ian Seol
  • 49
  • 5
  • Please reduce your code to the absolute minimum, that reproduces the issue. – slartidan Mar 17 '21 at 05:52
  • This looks like a request for someone to test and debug (and code review) your code. Or something. That's not a Question. If you want assistance with debugging, you work out what specific problem you want help with solving. Then you need to formulate a Question. For example: "This program is intended to solve the problem of . When I provide input X, I get output Y but I think the answer should be Z. Can you explain what is going wrong?" – Stephen C Mar 17 '21 at 07:54
  • The other thing is that you seem to have a number of problems in your code. The way to deal with this is to break down the big problem into smaller subproblems and solve them one at a time. Write the code for one subproblem at a time. Test and debug them one at a time. Ask questions .... one at a time. (You will find it is easier to do things one at a time rather than all at once.) – Stephen C Mar 17 '21 at 07:59
  • I apologize, first time using stackoverflow and first time to code... my professor is limiting us to use certain string methods(only length, concat, +, charAt, substring, and equals (or equalsIgnoreCase) and prohibited StringBuilder, indexOf, Arrays. I will ask questions instead of debugging requests in the future! – Ian Seol Mar 17 '21 at 10:48
  • @IanSeol Most programmers would declare the variables as close to the place where they are needed, instead of everything at the beginning of the method. – MC Emperor Mar 17 '21 at 11:10
  • I see. I will improve on that! thank you. and is there any tips regarding my problem 1, 2? I have edited my question to meet the guidelines. – Ian Seol Mar 17 '21 at 11:23

1 Answers1

0

You have several problems here:

  • Many of your operations are using the originalString after initial operations. As far as I can tell, there is no need to store the original string and use it in future operations. You store the input string in a single variable and perform operations on that same variable throughout the state of the program. For example, with a string "test", applying the "reverse" operation will return "tset", and applying reverse a second time will return "test". The original string is no longer relevant.
  • The code for "reverse", "replace last", and "remove all" is quite broken, even ignoring the use of originalString. Characters are being appended unnecessarily or onto incorrect strings. There are some bizarre flags and complex loops to accomplish what are relatively simple string operations.
  • The "Enter your command..." line is duplicating because you are using scanner.next(), scanner.nextInt(), etc. without consuming the newline token. You need to call scanner.nextLine() after using them. Refer to this related question.
  • Your scanner is not being closed after use. Read here about the try-with-resources statement.

You seem to have put some effort into this, so I'll offer some recommendations for your operations (note that I'm using a single String variable called "modifiableString" (instead of originalString & modifiedString) which is taken at the start of the program with scanner.nextLine() and used for every operation in the future). Feel free to try rewriting it yourself - I can assure you that there are several easier ways to do it than the kind of loops you've written so far.

reverse

modifiableString = new StringBuilder(modifiableString).reverse().toString();
System.out.println("The new string is: " + modifiableString);

replace first

String newModifiableString = modifiableString.replaceFirst(String.valueOf(enterReplaceChar), String.valueOf(enterNewChar));
if (newModifiableString.equals(modifiableString)) {
    System.out.println("The letter was not found in the word");
}
else {
    modifiableString = newModifiableString;
    System.out.println("The new string is: " + modifiableString);
}

replace last

int lastIndexOfReplaceChar = modifiableString.lastIndexOf(enterReplaceChar);
if (lastIndexOfReplaceChar == -1) {
    System.out.println("The letter was not found in the word");
}
else {
    modifiableString = modifiableString.substring(0, lastIndexOfReplaceChar) + enterNewChar + modifiableString.substring(lastIndexOfReplaceChar + 1);
    System.out.println("The new string is: " + modifiableString);
}

remove all

String newModifiableString = modifiableString.replaceAll(String.valueOf(enterRemoveChar), "");
if (newModifiableString.equals(modifiableString)) {
    System.out.println("Error: the letter you are trying to remove does not exist");
}
else {
    modifiableString = newModifiableString;
    System.out.println("The new sentence is: " + modifiableString);
}

remove

This one is a tad bit more complex as we need to use a regular expression matcher to iterate through the string until we find the character at the correct index or determine that the index is not possible given the number of instances of that character in the string.

Matcher matcher = Pattern.compile(String.valueOf(enterRemoveChar)).matcher(modifiableString);
if (!matcher.find()) {
    System.out.println("Error: the letter you are trying to remove does not exist");
}
else if (whichToRemove < 1 || whichToRemove > modifiableString.length()) {
    System.out.println("Error: the index you are trying to remove does not exist");
}
else {
    int characterIndex = 1;
    while (characterIndex < whichToRemove && matcher.find()) {
        characterIndex++;
    }
    if (characterIndex < whichToRemove) {
        System.out.println("Error: the index you are trying to remove does not exist");
    }
    else {
        int offset = matcher.end() - 1;
        modifiableString = modifiableString.substring(0, offset) + modifiableString.substring(offset + 1);
        System.out.println("The new string is: " + modifiableString);
    }
}
bliss
  • 297
  • 2
  • 8
  • Thank you so much for your help. I really appreciate the detailed recommended revisions that you provided. I am not too sure where I should put scanner. what would be the appropriate place for that? This program is for my intro to CS class and I am only limited to use certain string methods.(length, concat, +, charAt, substring, and equals are string methods I can use). Also, I cannot use index methods...StringBuilder, arrays, java,util,stream. Are there different ways to go about this problem? – Ian Seol Mar 17 '21 at 10:42
  • You would use try (Scanner scanner = new Scanner(System.in) { ... your code here ... } within your main method. As to your restrictions, you shouldn't have a problem coding similar methods with length, concat, charAt, substring, equals. I suggest that you step back and think carefully about the input string, the desired output string, and the necessary steps to apply the transformation before writing any code. Keep it simple and clean, test and debug your code along the way. – bliss Mar 17 '21 at 12:09