2011-03-08 65 views
0

假设行是字符串数组(如下面的向后应用程序中所示)。写一个for循环,在列中打印数组中字符串的长度,从数组中最后一个条目的长度开始,以数组元素的第0位结束。打印数组中的字符

例如,if线路由这三个字符串:

现在是
所有好男人的时间

你的代码应该打印:

如何打印在阵列中的字符数?我试过这个问题至少20次无济于事!请帮忙!

import java.util.*; 

public class Backwards { 
    public static void main(String[] args) { 
     String[] lines = new String[50]; 
     Scanner scan = new Scanner(System.in); 
     int pos = 0; 
     String t = " "; 

     while(t.length() > 0){ 
      t = scan.nextLine(); 
      lines[pos] = t; 
      pos++; 
     } 

     for(int j = pos - 1; j >= 0; j--){ 
      lines[j] = lines[j].toUpperCase(); 
      System.out.println(lines[j]); 
     } 
    } 
} 
+1

不应该这样下'homework'被标记? – 2011-03-08 02:58:35

+0

您的代码正在颠倒该数组中的字符串的内部。你确定你想以相反的方式获取每行中的字符数吗?如果是的话,请阅读下面的答案... – 2011-03-08 03:06:36

回答

1

这显然是一种分配,所以我不会为你写代码,但我会给你足够的提示让你走上正确的轨道。

您可以在数组中的字符串上反向循环,随时打印每个字符串的长度(您已经有了正确的反向循环)。

String对象的length() method应该是在你的println兴趣;-)

0

,你应该打印线[J]。长度(),否则,你会打印出输入字符串。
此外,使用arrayList将会更加方便。

0
1) Define an ArrayList, say arrLines. 
2) Read each line of the input, convert to string, if required using .toString();and 
    a)Calculate string length: strLength = <stringName>.length() 
    b)Add the length calculated in step a) to arrLines : arrLines.add(strLength); 
3) Print the arrLines in reverse: 
for(int i=arrLines.size();i>0;i--) 
{ 
    System.out.println(" "+arrLines.get(i)); 
} 
1

想想倒退:

for(int i = lines.length-1; i>=0; i--){ //starts the loop from the last array 
    System.out.println(lines[i].length()); //prints out the length of the string at that index 
}