Java program using String Tokenizer class

Write a Java program that reads a line of integers and displays each integer and sum of all integers using String Tokenizer class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.StringTokenizer;
import java.util.Scanner;
class tokens
{
	public static void main(String[] args)
	{
		Scanner input=new Scanner(System.in);
		String sentence=input.nextLine();
		String temp;
		int k,total=0;
		StringTokenizer s1=new StringTokenizer(sentence);
		System.out.println("Total Number of tokens:"+s1.countTokens());
		while(s1.hasMoreTokens())
		{
			temp=s1.nextToken();
			k=Integer.parseInt(temp);
			total+=k;
			System.out.print(k+"\t");
		}
		System.out.println("Sum of tokens :"+total);
	}
}

Output:

12 43 78 98
Total Number of tokens:4
12 43 78 98
Sum of tokens : 231

123 456 798
Total number of tokens:3
123 456 798
Sum of tokens:1377

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

2 thoughts on “Java program using String Tokenizer class

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in