簡體   English   中英

如何遍歷字符串列表以將每個單詞的最后一個字母更改為UpCase?

[英]How do I iterate through a list of Strings to change the last letter of each word toUpperCase?

這是為了功課。 我的方法執行后,似乎無法返回正確的代碼。 我不確定我的for循環是否正確迭代,或者我是否應該使用增強的for循環。 這是我的代碼:

/**
 * Replaces the words in the string so that every last character is upper case
 */
public void lastToUpperCase() 
{        
    for(int i=0;i>list.size();i++)
    {            
       String chopped = list.get(i);           
       String chopped1 = chopped.substring(chopped.length()-1,chopped.length());
       String screwed1 = chopped.substring(0,chopped.length()-1);
       String chopped2 = chopped1.toUpperCase();            
       String frankenstein = screwed1 + chopped2;
       System.out.print(frankenstein);          
    }         
}

這是應該打印的內容:

[PeteR, PipeR, pickeD, A, pecK, oF, pickleD, peppers.]

我將從for-each循環開始,並使用StringBuilder (用於setCharAt(int, char) )和類似的東西

for (String str : list) {
    StringBuilder sb = new StringBuilder(str);
    sb.setCharAt(sb.length() - 1, Character.toUpperCase(//
            sb.charAt(sb.length() - 1)));
    System.out.print(sb);
}

與問題

for(int i=0;i>list.size();i++)

i不是>list.size()所以沒有輸入循環。

for(int i=0;i<list.size();i++)

詳細闡述其他人對for的評論:第二個表達式被視為“ while”條件; 也就是說, 表達式為真 ,循環繼續進行。 一旦表達式變為假,循環就會終止,程序將在循環后進入語句。 編寫方式(請注意,使用多余的空格更容易閱讀,而不是將所有內容卡在一起):

for (int i = 0; i > list.size(); i++)

i從0開始。但是0 > list.size()false ,因此它立即退出循環-也就是說,它甚至從不執行列表主體。

我想到了:

/**
 * Replaces the words in the string so that every last character is upper case
 */
public void lastToUpperCase() 
{
    for(int i=0; i<list.size(); i++)
    {            
        String chopped = list.get(i);           
        String screwed = chopped.substring(chopped.length()-1,chopped.length());
        String frankenstein = screwed.toUpperCase();
        String von = list.set(i, chopped.substring(0, chopped.length()-1) + frankenstein);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM