0
How to read unknown number of inputs from the user in Java?
I need to read unknown number of inputs from the user. And show the sum of the inputs as a result. Ex: Input: 23 14 67 43 17 12 75 Output: 251 (Explanation = 23+14+67+43+17+12+75 = 251) (Code has to read input numbers till the user press enter)
4 Answers
+ 1
Mohamed Wasim
Just take numbers with space as a string then split that string into an array and calculate sum.
0
Well, do you know how to count?
0
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
int sum=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the length");
int n=sc.nextInt();
int arr[]=new int[n];
System.out.println ("Enter the element");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
//sum=sum+arr[i];!
}
System.out.println("sum of array elments="+sum);
}
}
0
The scannner class has a method call hasNext(), this will keep asking for input until the user moves for the next line by cliking enter.
import java.util.*;
public class Sum{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int sum=0;
while(sc.hasNext()){
int number=sc.nextInt();
sum+=number;
}
System.out.println(sum);
}
}