Written by Sai Sameera Thota on June 19, 2013 in Java > Programming

Java Program to Read line of Integers and Display Sum

GET ALERTS:

Get our Latest updates delivered to your mailbox!

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

{ 1 comment… read it below or add one }

bindu February 1, 2017 at 11:21 pm

really amazing..your help made me done with this program succesfully

Reply

Leave a Comment

Previous post:

Next post: