简体   繁体   English

如何遍历字符串列表以将每个单词的最后一个字母更改为UpCase?

[英]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. 我不确定我的for循环是否正确迭代,或者我是否应该使用增强的for循环。 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-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);
}

The issue with 与问题

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

is that i is not >list.size() so your loop isn't entered. i不是>list.size()所以没有输入循环。

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; 详细阐述其他人对for的评论:第二个表达式被视为“ while”条件; 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从0开始。但是0 > list.size()false ,因此它立即退出循环-也就是说,它甚至从不执行列表主体。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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