Java Case切换器 [英] Java Case Switcher

查看:80
本文介绍了Java Case切换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在编写一个小小的返回程序,该程序用于切换字符串中字符的大小写,因此HELLo变为hElLo,hello变为HeL10,aaa变为AaA。我有点麻烦。我仍然是新手,正在学习Java,因此很抱歉,如果这违反了规则:

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;
 }


推荐答案

所以我设法做到了

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;
 }

我添加了一个'flipFlop'方法来跟踪迭代,而方法'切换器根据最后一个字符的条件在大写和小写之间切换。 (当字符串中的最后一个字符为大写时,lastUp为true。)

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).

这篇关于Java Case切换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆