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
4 Réponses
+ 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
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); } }
1st May 2024, 11:23 AM
Simon John S