Search code examples
javastringcharreturncase-sensitive

Java Case Switcher


So I'm writing a little return program that switches the case of characters in a string, so HELLo becomes hElLo and hello becomes HeLlO, and aaa becomes AaA. I'm having a bit of trouble though. I'm still new and learning java, so sorry if this breaks rules:

public static String altCase(String text){
      String str = "";
      for (int i = 0; i <= text.length()-1; i++)
      {
        char ch = text.charAt(i);
        boolean lastIsUpperCase = true;
        if(Character.isUpperCase(i-1))
        {
          lastIsUpperCase = true;
        }
        else if(Character.isLowerCase(i-1))
        {
          lastIsUpperCase = false;
        }

        if(lastIsUpperCase)
        {
          str += Character.toLowerCase(ch);
        }   
        else if (!lastIsUpperCase)
        {
          str += Character.toUpperCase(ch);
        }
      }
      return str;
 }

Solution

  • So I managed to do it.

    public static String altCase(String text){
          String str = "";
          str += Character.toUpperCase(text.charAt(0));
          for (int i = 1; i <= text.length()-1; i++)
          {
            char ch = text.charAt(i);
            boolean lastUp = flipFlop(i);
            char temp = switcher(ch, lastUp);
            str+=temp;
          }
          return str;
     }
     public static boolean flipFlop (int i){
          boolean bool = true;
          if(i==1){
            bool = true;
          }
          else if((i%2)==0)
          {
               bool = false;
          }
          else if((i%2)!=0)
          {
               bool = true;
          }
          return bool;
     }
     public static char switcher (char ch, boolean lastUp){
       char temp = ch;
       if(lastUp){
            temp = Character.toLowerCase(ch);
       }
       else if (lastUp==false){
         temp = Character.toUpperCase(ch);
       }
       return temp;
     }
    

    I added a 'flipFlop' method to track the iterations, and the method 'switcher' changes between upper and lower case based on the condition of the last char. (lastUp is true when the last character in the string is uppercase).