0

So the problem that I am currently running into is that the statement "Enter your command (reverse, replace first, replace last, remove all, remove)" is printing twice after I go through all the steps.

What I believe is happening is the loop is executing twice but I don't know why. Any help would be appreciated in solving this problem. Sorry in advance if my code formatting is bad still learning how to properly format.

import java.util.Scanner;

public class StringChangerenter {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        // Output Variables
        String userInput = "";

        // Variables
        String removeChar = "", removeAllChar = "";
        int removeIndex = 0;

        // First Output
        System.out.println("Enter the string to be manipulated");
        userInput = keyboard.nextLine();
        String command = "";

        // While loop
        while (!command.equalsIgnoreCase("quit")) {
            // Output
            System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
            command = keyboard.nextLine();
            if (command.equalsIgnoreCase("remove")) {
                System.out.println("Enter the character to remove");
                removeChar = keyboard.nextLine();
                int totalCount = 0;
                for (int j = 0; j < userInput.length(); j++) {
                    if (userInput.charAt(j) == removeChar.charAt(0)) {
                        totalCount = totalCount + 1;
                    }
                }
                System.out.println("Enter the " + removeChar
                        + " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
                removeIndex = keyboard.nextInt();
                int currentIndex = 1;
                if (removeIndex <= totalCount) {
                    for (int i = 0; i < userInput.length(); i++) {
                        if (userInput.charAt(i) == removeChar.charAt(0)) {
                            if (currentIndex == removeIndex) {
                                String firstpartOfString = userInput.substring(0, i);
                                String secondpartOfString = userInput.substring(i + 1, userInput.length());
                                System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
                                userInput = firstpartOfString + secondpartOfString;
                                break;
                            } else {
                                currentIndex = currentIndex + 1;
                            }
                        }
                    }
                } else {
                    System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
                }
                // Remove All Code

            } else if (command.equalsIgnoreCase("remove all")) {
                System.out.println("Enter the character to remove");
                removeAllChar = keyboard.next();
                String newString = "";
                for (int i = 0; i < userInput.length(); i++) {
                    if (userInput.charAt(i) != removeAllChar.charAt(0)) {
                        newString = newString + userInput.charAt(i);
                    }
                }
                userInput = newString;
                System.out.println("The new sentence is " + userInput);
            }
            // Bracket for while loop
        }
    }
}
Daniel Widdis
  • 5,479
  • 7
  • 27
  • 46
ashah24
  • 13
  • 3

2 Answers2

1

what is happening is, the condition for you while loop is

while (!command.equalsIgnoreCase("quit"))

which in english mean, as long as command is not equal to "quit" then run this loop.

Inside the loop, command is never actually set to "quit". ex if I give input string as "abcde" and ask to remove "c" at position 1. Then your logic sets command to "remove" here

command = keyboard.nextLine();

and then prints the final value as "abde". Now when the loop ends, command is still "remove" and hence the loop executes again.

A possible solution is to explicitly ask the user if he wants to retry using a do while loop. Also just a tip, i see you have used nextInt. It is advisable to use a nextLine immediately after next int. see this for the reason why: Java Scanner doesn't wait for user input

this is what you code would be if you explicitly took user consent if you want to run any more commands:

public static void main (String[] args) throws java.lang.Exception
    {
    Scanner keyboard = new Scanner(System.in);
        // Output Variables
        String userInput = "";

        // Variables
        String removeChar = "", removeAllChar = "";
        int removeIndex = 0;

        // First Output
        System.out.println("Enter the string to be manipulated");
        userInput = keyboard.nextLine();
        String command = "";
        String retry = "";
        // While loop
        do {
            // Output
            System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
            command = keyboard.nextLine();
            if (command.equalsIgnoreCase("remove")) {
                System.out.println("Enter the character to remove");
                removeChar = keyboard.nextLine();
                int totalCount = 0;
                for (int j = 0; j < userInput.length(); j++) {
                    if (userInput.charAt(j) == removeChar.charAt(0)) {
                        totalCount = totalCount + 1;
                    }
                }
                System.out.println("Enter the " + removeChar
                        + " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
                removeIndex = keyboard.nextInt();
                keyboard.nextLine();
                int currentIndex = 1;
                if (removeIndex <= totalCount) {
                    for (int i = 0; i < userInput.length(); i++) {
                        if (userInput.charAt(i) == removeChar.charAt(0)) {
                            if (currentIndex == removeIndex) {
                                String firstpartOfString = userInput.substring(0, i);
                                String secondpartOfString = userInput.substring(i + 1, userInput.length());
                                System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
                                userInput = firstpartOfString + secondpartOfString;
                                break;
                            } else {
                                currentIndex = currentIndex + 1;
                            }
                        }
                    }
                } else {
                    System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
                }
                // Remove All Code

            } else if (command.equalsIgnoreCase("remove all")) {
                System.out.println("Enter the character to remove");
                removeAllChar = keyboard.next();
                String newString = "";
                for (int i = 0; i < userInput.length(); i++) {
                    if (userInput.charAt(i) != removeAllChar.charAt(0)) {
                        newString = newString + userInput.charAt(i);
                    }
                }
                userInput = newString;
                System.out.println("The new sentence is " + userInput);

            }
            System.out.println("Do you want to go again?");
            retry = keyboard.nextLine();
            // Bracket for while loop
        }while("yes".equalsIgnoreCase(retry));
    }
Vardaan Sharma
  • 917
  • 8
  • 18
  • Simple debugging tip: just print the value of command variable at the end of the while loop. This will show you what value is being evaluated by the loop. – Vardaan Sharma Mar 03 '19 at 23:38
  • @Vardann Sharma I understand the the answer you have given but I don't understand how I would fix this. Would I have to set the command equal to quit in the while loop? – ashah24 Mar 03 '19 at 23:49
  • @VardaanSharma you're putting a band aid on the problem without addressing the root cause. See my answer for the reason for the duplicates. – Daniel Widdis Mar 04 '19 at 02:01
  • @DanielWiddis In my answer, I have already mentioned to use NextLine() after nextInt() to process the newline character along with the relevant stackoverflow link where this is discussed in more detail. – Vardaan Sharma Mar 04 '19 at 02:03
  • @VardaanSharma you are focusing on the value of `command` which is irrelevant. I see that you did mention the correct answer to the user's problem in the second sentence of a paragraph starting with "Also, just a tip..." and "it is advisable", framing it like a suggestion when it is, in fact, the problem that @ashah24 is trying to solve. Your solution gives the user nothing to correct, which has been noted in this comment thread. – Daniel Widdis Mar 04 '19 at 02:09
  • Also @VardaanSharma your fix only addresses the int, not the single character reading in the second branch. Your "go again" prompt doesn't address the problem at all. When it asks what character remove I could type `x` which would remove the `x`es and then jump to the "go again" prompt with an empty string -- which would not match "Yes" and exit the loop even if I wanted to go again! That's my point, while you mentioned the real problem, the main focus of your fixes doesn't match it. – Daniel Widdis Mar 04 '19 at 02:14
1

The reason you are getting two entries after you've processed a character, is that you have not fully read the line containing the character.

Specifically, you use keyboard.nextInt(); in the upper branch, and keyboard.next(); in the lower branch. While these read the next integer and character, respectively, they do not process the end of line marker.

Then when you reach the top of the loop, you call keyboard.nextLine() which processes whatever characters occurred after the int (or character, in the remove all case) until the end of line marker. With the expected user input, that's just an empty string.

To fix this, you need to ensure you read all the way through the keyboard.nextLine() in the cases where you are reading only integers, or a single character.

Daniel Widdis
  • 5,479
  • 7
  • 27
  • 46