How to read unknown number of inputs from the user in Java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)

2nd May 2021, 2:58 PM
Mohamed Wasim
Mohamed Wasim - avatar
3 Answers
+ 1
Mohamed Wasim Just take numbers with space as a string then split that string into an array and calculate sum.
2nd May 2021, 4:02 PM
A͢J
A͢J - avatar
0
Well, do you know how to count?
2nd May 2021, 3:27 PM
zxtychj
zxtychj - avatar
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); } }
2nd May 2021, 5:17 PM
Aditya
Aditya - avatar