2017-03-02 123 views
1

下面是我的代码,它检查传入的模型并相应地修改源,检查它的ALLCAPS或Firstcap。我遇到的问题是模型包含一个符号,例如matchCase( “我”, “苹果”)。这将返回苹果,当它应该返回苹果。另一方面,如果我使用“Im”,它将正确地修改为“Apple”。有没有办法我可以修改它的工作。我试图运行的几种方法,但我一直陷入字符串循环问题

public static String matchCase(String model, String source){ 
 
    boolean o = true; 
 
    if(model.toUpperCase().equals(model)){ 
 
     source = source.toUpperCase(); 
 
    } 
 
    if(Character.isUpperCase(model.charAt(0))){ 
 
     for(int i=1;i<model.length();i++){ 
 
     if(Character.isLowerCase(model.charAt(i)) == false){ 
 
      o = false; 
 
     } 
 
     } 
 
    // if(o == model.length()-1){ 
 
     if(o == true){ 
 
     String can = ""; 
 
     for(int j=0;j<source.length();j++){ 
 
      if(j==0){ 
 
      can += Character.toUpperCase(source.charAt(j)); } 
 
      else{ 
 
      can += source.charAt(j); 
 
      } 
 
     } 
 
     source = can; 
 
// Character.toUpperCase(source.charAt(0)); 
 
     
 
    } 
 
    } 
 
    
 
    return source; 
 
    } 
 
}

+0

能否请你解释更加清晰的方式逻辑?你到底想要达到什么目标? –

+0

*这将返回苹果,当它应该返回苹果。另一方面,如果我使用“Im”,它将正确地修改为“Apple”。*这听起来很不错。有什么问题? – nullpointer

+0

它以字符串作为模型,其中一个来源。比方说模型是“检查”,来源是“你好”。它将检查模型并将源修改为HELLO,因为模型全部大写。同样,如果它的模型是“Check”并且源代码是“hello”,它会将源代码修改为“Hello”。 –

回答

1

我认为你的问题来自于一个事实,即

Character.isLowerCase('\'') // is false 

你应该改变这种测试

if(Character.isLowerCase(model.charAt(i)) == false) 

通过

if(Character.isUpperCase(model.charAt(i))) 
+0

为了说明,请查看:https://www.tutorialspoint.com/java/character_islowercase.htm – DVT

+0

谢谢,这是做到了。 :) –

+0

@BasilSindhu如果您认为它是正确的,请接受答案。 – DVT

0

如果你知道你的模型总是要大写或firstcap你不能做这样的事情:

public static String matchCase(String model, String source){ 
    if(model.toUpperCase() == model) 
     return source.toUpperCase(); 
     // capitalize the first letter of source and send back 
    return Character.toUpperCase(source.charAt(0)) + source.substring(1); 
    }