打印数组中的字符

时间:2011-03-08 02:47:04

标签: java arrays string

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

例如,如果行包含这三个字符串:

  

现在是   时间
  为所有好人

你的代码应该打印出来:

  

16
  8
  6

如何打印数组中的字符数?我试过这个问题至少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]);
        }
    }
}

4 个答案:

答案 0 :(得分:1)

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

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

String对象的length() method应该是有意义的; - )

答案 1 :(得分: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
}

答案 2 :(得分:0)

在你的println中,你应该打印[j] .length()行,否则你将打印输入字符串。
此外,使用arrayList会更方便。

答案 3 :(得分: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));
 }
相关问题