[英]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.