Java Program to Read line of Integers and Display Sum

Question:
Write a Java Program that reads a line of integers, and then displays each integer, and
the sum of all the integers (Use StringTokenizer class of java.util).

Solution:
The program takes a line of integers as input and displays the number of integers,each integer and also sum of all the integers using the StringTokenizer class of java.util package.

Java Program to Read line of Integers and Display their Sum

import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
class StringTokenizerEx
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		//Scanner objScanner = new Scanner(System.in);
		System.out.print("\nEnter A Line Of Integers:");
		//String line = objScanner.nextLine();
        String line = br.readLine();
		StringTokenizer st = new StringTokenizer(line);
        System.out.println("\nNumber of tokens : "+st.countTokens());
		long sum = 0;
		System.out.print("\nTokens are : \n" );
		while (st.hasMoreTokens())
		{
            long i = Long.parseLong(st.nextToken());
			System.out.print(i + "\n");
			sum = sum + i;
		}
		System.out.println("\nThe Sum Is :" +sum);

	}
}

Output:
StringTokenizerEx

Leave a Reply