开发者

Print the Characters in an Array

开发者 https://www.devze.com 2023-02-15 05:24 出处:网络
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 e

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();
     开发者_StackOverflow社区       System.out.println(lines[j]);
        }
    }
}


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


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
}


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

精彩评论

暂无评论...
验证码 换一张
取 消