Java program that reads a line of integers, and displays each integer, and the sum of all the integers ( uses StringTokenizer class of java.util)

 

import java.util.*;

class StringTokenizerDemo {
	public static void main(String args[]) {
		int n;
		int sum = 0;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter integers with one space gap:");
		String s = sc.nextLine();
		StringTokenizer st = new StringTokenizer(s, " ");
		while (st.hasMoreTokens()) {
			String temp = st.nextToken();
			n = Integer.parseInt(temp);
			System.out.println(n);
			sum = sum + n;
		}
		System.out.println("sum of the integers is: " + sum);
		sc.close();
	}
}

 OUTPUT:

Enter integers with one space gap:
10 20 30 40 50
10
20
30
40
50
sum of the integers is: 150

Write a java program that read a line of integer, and then displays each integer, and the sum of all the integers ( use StringTokenizer class of java.util)


Buy Head First Java

Best Book for Java

Beginner's Book