0

Hello, how can I add more than one number in the console using a scanner by writing one line code?

2nd Jan 2023, 2:02 PM
Barxudan Abbas
Barxudan Abbas - avatar
1 Answer
+ 10
you can use a loop to repeatedly prompt the user for a number and add it to a running total. Here is an example of how you could do this in one line of code: int sum = 0; while (scanner.hasNextInt()) { sum += scanner.nextInt(); } You can also use a for loop to achieve the same result: int sum = 0; for (int i = 0; scanner.hasNextInt(); i++) { sum += scanner.nextInt(); }
2nd Jan 2023, 2:05 PM
Sadaam Linux
Sadaam Linux - avatar