简体   繁体   中英

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

This is for homework. I can't seem to return the correct code when my method gets executed. I'm not sure if my for loop is iterating properly or if i'm supposed to use the enhanced for loop. This is my code:

/**
 * 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);          
    }         
}

This is what is supposed to be printed:

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

I would start with a for-each loop and use a StringBuilder (for setCharAt(int, char) ) and something like

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

The issue with

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

is that i is not >list.size() so your loop isn't entered.

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

To elaborate on others' comments about the for : The second expression is treated like a "while" condition; that is, the loop keeps going while the expression is true. As soon as the expression becomes false, the loop terminates, and the program goes to the statement after the loop. The way you wrote this (note that it's easier to read with extra spaces, instead of all jammed together):

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

i starts out as 0. But then 0 > list.size() is false , so it exits the loop immediately--that is, it never executes the list body even once.

I figured it out:

/**
 * 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM