Search code examples
javacomputer-science

Are there any ways to make this simple program more efficient?


The program is pretty simple: it takes a string and replaces the vowels with '_' then prints the reversed string. I am just looking at ways to make my code more professional and would like some tips.

import java.util.Scanner;

public class reverse_string {

    public static void main (String[] args){

        Scanner scan = new Scanner(System.in);

        String input, reverseInput;
        String legolas = new String();

        System.out.println("Enter any input");

        input = scan.nextLine();

        StringBuilder newString = new StringBuilder(input);

        System.out.println("The data you entered is: "+input);

        for (int i =0; i <input.length();i++){

            if (testIfVowel(input.charAt(i))){
                newString.setCharAt(i,'_');
            }
            else{
                newString.setCharAt(i, input.charAt(i));
            }

        }
        for(int i = input.length()-1;i>=0;i--){
            legolas = legolas +input.charAt(i);
        }

        reverseInput=reverseOrder(newString);

        System.out.println("Your old data was: "+input+"\nYour new data is: "+newString +"\nYour old data in reverse is: "+legolas+"\nYour new data in reverse is: "+ reverseInput);

    }



    public static boolean testIfVowel(char x){
        if(x =='a'||x=='A'||x=='e'||x=='E'||x=='i'||x=='I'||x=='o'||x=='O'||x=='u'||x=='U'){
            return true;
        }
        else{
            return false;
        }
    }

    public static String reverseOrder(StringBuilder x){

        String string= new String();

        for(int i = x.length()-1;i>=0;i--){

            string = string + x.charAt(i);
        }

        return string;
    }
}

Solution

  • I would suggest that your logic is unnecessarily complex. For instance, do you really need a testIfVowel method that is only used one time? I doubt it.

    I'd do something like this (pseudocode):

    resultString = '';
    for (i = 0; i < length(s); i++) {
      if ("AEIOUaeiou".indexOf(s[i]) != 0) {
        resultString = '_' + resultString;
      } else {
        resultString = s[i] + resultString;
      }
    }
    

    (You could do this in any language.)

    Notice how the test-for-vowels is now simple and obvious, clearly working for both upper- and lower-case versions. And, how the "reversed string" is created, one character at a time, simply by inserting the new character at the front of the initially-empty resultString.

    Perhaps most importantly (to me), this version "reads very easily." I don't have to look at much code to desk-check that it will work. It, if you will, "gets straight to the point."

    Much cleaner, I think ...