2013-02-20 68 views
0

該方法取任何名稱並測試字符是元音還是輔音。如果它是一個元音,它會使字符大寫,如果是輔音,則會使字符變爲小寫。有什麼想法嗎?我不知道如何在if語句中添加.toUpperCase.toLowerCaseJava - 根據字符串是否爲元音轉換字符串中的字符

public static void parsing(String name[]) 
{ 
    String temp = name[0]; 

    int i = 0; 
    for(i = 0; i < temp.length(); i++) 
    { 
     if(temp.charAt(i) == 'a' || temp.charAt(i) == 'A' || 
      temp.charAt(i) == 'e' || temp.charAt(i) == 'E' || 
      temp.charAt(i) == 'i' || temp.charAt(i) == 'I' || 
      temp.charAt(i) == 'o' || temp.charAt(i) == 'O' || 
      temp.charAt(i) == 'u' || temp.charAt(i) == 'U') 
     { 
     System.out.print(temp.charAt(i).toUpperCase); 
     }//Obviously wrong but I don't know what to do. 
      else 
      { 
      System.out.print(temp.charAt(i).toLowerCase); 
      }//Obviously wrong but I don't know what to do.  
    } 
+2

那麼當你運行這個時會發生什麼? – Dutts 2013-02-20 17:29:07

+0

String.equalsIgnoreCase是你的朋友 – NimChimpsky 2013-02-20 17:29:49

回答

2

要轉換單個字符使用來自Character類的方法:

System.out.print(Character.toUpperCase(temp.charAt(i))); 
System.out.print(Character.toLowerCase(temp.charAt(i))); 
+0

這很好用,比其他答案短得多。謝謝,約翰。 – 2013-02-20 18:03:09

1

創建兩個最終數組 - 第一個是元音,第二個是輔音。然後檢查循環中的當前字符是否是元音或輔音,並進行適當的更改。

0

你是打你的頭字符串是不可改變的。重建生成的字符串。 A(位不理想)的解決方案是:

public static void parsing(String[] names) 
{ 
    for (int i = 0; i < names.length; ++i) { 
     names[i] = chAngEd(names[i]); 
    } 
} 

private static String chAngEd(String s) { 
    String result = ""; 
    for (int i = 0; i < s.length(); ++i) { 
     char ch = s.charAt(i); 
     if (ch == 'a' || ...) { 
      ch = Character.toUpperCase(ch); 
     } else { 
      ch = ... 
     } 
     result += ch; 
    } 
    return result; 
} 
0
public static void parsing(String names[]){ 
    for (int i=0; i<names.length; ++i){ 
     names[i] = capitaliseConsts(names[i]); 
    } 
} 


private static String capitaliseConsts(String name){ 
    StringBuilder sb = new StringBuilder(); 
    Character c; 

    for (int i=0; i<name.length(); ++i){ 
     c = name.charAt(i); 
     if (c.equalsIgnoreCase('a') || 
      c.equalsIgnoreCase('e') || 
      c.equalsIgnoreCase('i') || 
      c.equalsIgnoreCase('o') || 
      c.equalsIgnoreCase('u')){ 

      sb.append(Character.toUpperCase(c)); 
     } 
     else{ 
      sb.append(Character.toLowerCase(c)); 
     } 
    } 
    return sb.toString(); 
} 
0
String vowelsArray = "aeiuo"; 
String constantsArray = "uppercase constants"; 
int stringLength = name.length(); 
String givenNameCopy = name.ToString(); 
for(int i = 0; i < stringLength; i++){ 
if(vowelsArray.contains(givenNameCopy[i])) 
    then uppercase 
else if(constantsArray.contains(givenNameCopy[i])) 
    then lowercase 
else 
    continue; 

希望這會有所幫助。