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