简体   繁体   中英

Print the Characters in an Array

Suppose lines is an array of strings (as in the Backwards application below). Write a for loop that prints, in a column, the lengths of the strings in the array, starting with the length of the last entry in the array, and ending with the array element at position 0.

For example, if lines consists of these three strings:

Now is
the time
for all good men

your code should print:

16
8
6

How do I print the number of characters in an array? I've attempted this problem at least 20 times to no avail!!! Please help!

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

Think about it going backwards:

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
}

This is clearly some sort of assignment, so I won't write the code for you, but I will give you enough of a hint to get you on the right track.

You could loop in reverse over the strings in the array, printing the length of each one as you go (you already have the looping in reverse correct).

The length() method of String objects should be of interest ;-)

in your println, you should print lines[j].length() or else, you'll print out the input string.
Also, using an arrayList will be much more convenient.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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