Write a program (Java) ....?

Write a program CharCount.java that reads in an integer “n”. Following

this, your code should read in the next “n” lines of input. For every line of input your

code should output the line number in a field of width 5 (call the first line number 0)

followed by a space and a vertical bar, followed by the line of input, followed by

another vertical bar. After processing all of the “n” lines of input, your code should

output the number of lines of input and the total number of characters read in the

input lines.

For example, for the input

3

This

and that

and the other

Your program should output

0 |This|

1 |and that|

2 |and the other|

number of lines : 3

number of characters: 24

Update:

Thank you for your answer, but we didn't yet learn arrays. Is there any way not to use arrays?

Comments

  • import java.util.*;

    public class Example {

    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print("How many lines: ");

    int lines = sc.nextInt();

    sc.nextLine(); // needed to clear buffer

    String[] array = new String[lines];

    for(int x=0;x<lines;x++){

    System.out.print("Enter string: ");

    array[x] = sc.nextLine();

    }

    int chars = 0;

    for(int x=0;x<lines;x++){

    System.out.format("%5d |" + array[x] + "|%n",x);

    chars = chars + array[x].length();

    }

    System.out.println("Number of lines: " + lines);

    System.out.println("Number of characters: " + chars);

    }

    }

    I referred this page to for reading multiple inputs from a scanner:

    http://javacodex.com/Reading-Input/Reading-Multipl...

Sign In or Register to comment.