Write a Java program that reads a line of integers and then displays each integer, and the sum of all the integers.
Program Code in JAVA:
import java.io.*;
import java.util.*;
class StringToken
{
public static void main(String[] args) throws Exception
{
int i=0,sum=0;
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter the Line of Integer Separated by Space");
String str=dis.readLine();
int n=str.length();
int a[]=new int[n];
StringTokenizer st=new StringTokenizer(str);
while(st.hasMoreTokens())
{
a[i]=Integer.parseInt(st.nextToken());
System.out.println("a["+i+"]= "+a[i]);
i++;
}
for(i=0;i<n;i++)
sum+=a[i];
System.out.println("Sum is = "+sum);
}
}
Program Output:
c:\java>javac StringToken.java
c:\java>java StringToken
Enter the Line of Integer Separated by Space
1 2 3 4 5
a[0]= 1
a[1]= 2
a[2]= 3
a[3]= 4
a[4]= 5
Sum is = 15
Post A Comment:
0 comments: