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

2 Responses to “Java program using String Tokenizer class”

Leave a Reply