2
\$\begingroup\$

Assignment:

Create a program Substitute that gets a sentence from the user and replaces every occurrence of the word java (uppercase, lowercase, or a combination) with JAVA. You may not change the original content of the sentence except for the substitution of JAVA. Note that Java could appear in a larger word such as JavaScript, openjava, javazon, Ajjavara, Javanese. You MUST use the substring method to do this. Display the modified sentence. The program must keep running until the user enters "quit" (upper- or lowercase). I cannot use replace method or regex for this program.

Code:

import java.util.Scanner;

public class Substitute
{
    public static void main(String[] args)
    {
        System.out.println("Program written by Eric Wessel");
        System.out.println("*******************************");

        System.out.println("Program that reads in a sentence and replaces every occurrence of the word \"java\" with \"JAVA\" in the sentence.");
        System.out.println("************************************************************************************************************");

        // Declare and initialize variables
        String left, right, sub = "", result = "";
        int index, indexOfRight;

        // Prompt for a sentence with a word "java" and store it in sentence String variable
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a sentence with a word \"java\" and replaces every occurrence of it with \"JAVA\" or type \"quit\" to quit: ");
        String sentence = input.nextLine();

        // While loop 1 for the program to keep running until the user enters quit.
        while(!(sentence.equalsIgnoreCase("quit")))
        {   
            // Find the index of first java occurrence after converting sentence to uppercase. 
            index = sentence.toUpperCase().indexOf("JAVA");

            // If there is a word "java" in the sentence, then separates left and right parts of word java, converts the word java to 
            // uppercase and store it in sub and then concatenates in the order: left + sub + right. Otherwise it will print:
            // "There is no word "java" in the sentence" and prompt for next sentence.
            if(index != -1)
            {
                // While loop 2 to continue until index returns -1 (or no more word java in the sentence).
                while(index != -1) 
                {
                    left = sentence.substring(index, index + 4);
                    right = sentence.substring(index + 4);
                    indexOfRight = sentence.indexOf(right, index + 4);

                    if(indexOfRight <= 0 || indexOfRight >= sentence.length())
                    {
                        sub = sentence.toUpperCase().substring(index, index + 4);

                        if(result == "")
                        {
                            result = sentence.substring(0, index) + sub;
                        }
                        else
                        {
                            result = result.substring(0, index) + sub;
                        }

                        index = -1;
                    }

                    else if(indexOfRight > 0 && indexOfRight < sentence.length())
                    {
                        sub = sentence.toUpperCase().substring(sentence.indexOf(left, index), sentence.indexOf(right, index + 4));

                        if(result == "")
                        {
                            result = sentence.substring(0, (sentence.indexOf(left, index))) + sub + sentence.substring(sentence.indexOf(right, index + 4));
                        }

                        else
                        {
                            result = result.substring(0, (sentence.indexOf(left, index))) + sub + sentence.substring(sentence.indexOf(right, index + 4));
                        }

                        index = sentence.toUpperCase().indexOf("JAVA", index + 4);
                    }

                    if(index == -1)
                    {
                        System.out.println(result);
                    }
                } // end of while loop 2

                System.out.print("Please enter a sentence with a word \"java\" and replaces every occurrence of it with \"JAVA\" or type \"quit\" to quit: ");
                sentence = input.nextLine();
                index = sentence.toUpperCase().indexOf("JAVA");
                result = "";
            }
            else
            {
                System.out.println("There is no word \"java\" in the sentence.");
                System.out.print("Please enter a sentence with a word \"java\" and replaces every occurrence of it with \"JAVA\" or type \"quit\" to quit: ");
                sentence = input.nextLine();
                index = sentence.toUpperCase().indexOf("JAVA");
                result ="";
            }   
        } // end of while loop 1
    }
}

Output:

$ java Substitute
Program written by Eric Wessel
*******************************
Program that reads in a sentence and replaces every occurrence of the word "java" with "JAVA" in the sentence.
************************************************************************************************************
Enter a sentence with a word "java" and replaces every occurrence of it with "JAVA" or type "quit" to quit: javaScript, openjava, javazon, Ajjavara, JavaneseJavaScript, openjava, javazon, Ajjavara, Javanese

JAVAScript, openJAVA, JAVAzon, AjJAVAra, JAVAneseJAVAScript, openJAVA, JAVAzon, AjJAVAra, JAVAnese

Please enter a sentence with a word "java" and replaces every occurrence of it with "JAVA" or type "quit" to quit: javajava

JAVAJAVA

Please enter a sentence with a word "java" and replaces every occurrence of it with "JAVA" or type "quit" to quit: quit
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

Your code is pretty complicated. The simplest, albeit slow algorithm is:

public static String toUpper(String str, String word) {
    String result = "";
    int i = 0;
    while (i < str.length()) {
        if (i + word.length() <= str.length()
            && str.substring(i, i + word.length()).equalsIgnoreCase(word)) {

            result += word.toUpperCase();
            i += word.length();
        } else {
            result += str.charAt(i);
            i++;
        }
    }
    return result;
}

The above code may or may not work as expected for Turkish (dotless i) and German (Straße -> STRASSE), but all other languages should be fine.


Your code contains many duplicate lines, which is considered bad style because some day, someone will change one of the lines but not the other, and then your code does almost the same in the two different cases.

Do not compare strings with ==. In Java you have to write it in an uglier way: str1.equals(str2), or in your particular case str.isEmpty().

\$\endgroup\$
3
  • \$\begingroup\$ To improve performance while still using substring (sigh), you could uppercase outside the while loop and use equals() \$\endgroup\$ Nov 28, 2017 at 7:50
  • \$\begingroup\$ Nice seeing the mention of uppercasing changing the number of characters and/or removing/adding accents. Here it would be better to do toUpperCase(Locale.ENGLISH) \$\endgroup\$
    – Joop Eggen
    Nov 28, 2017 at 8:44
  • 1
    \$\begingroup\$ @RobAu you're completely correct. In this case I did the toUpperCase inside the loop because it more closely matches the English description of the algorithm. My primary goal was to make the code understandable for beginners, and having too many variables makes that difficult. If I had aimed for runtime performance, the code would have looked completely different. If I had aimed for shortness (without any restrictions), I would hqve chosen return str.replaceAll("(?-i)java", "JAVA"). \$\endgroup\$ Nov 28, 2017 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.