Electrofriends

Java program using String Tokenizer class

by Ranjith | October 2nd, 2009.

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


Share and Enjoy:
  • Digg
  • Technorati
  • StumbleUpon
  • Twitter
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit
  • Mixx
  • Yahoo! Buzz
  • LinkedIn
  • NewsVine
  • RSS
  • email
Similar Posts:

Leave a Reply

Share and enjoy

    • Digg
    • Facebook
    • Technorati
    • StumbleUpon
    • Twitter
    • Reddit
    • del.icio.us
    • Yahoo! Buzz
Copyright©2009 www.electrofriends.com All Rights Reserved. Powered by Dhyeya