0

How to put and sum numbers with scanner?? Java

Can someone write code and explain plz, Thank you

10th Oct 2018, 9:35 PM
Uros Ristic
2 Respuestas
0
0 down vote favorite Trying to figure out how I would take any amount of inputted numbers from a user and add them together Example user input: 1 2 3 4 Sum = 10 The user can put any amount of numbers in not a specified amount so if he wanted to add 1 2 3 4 5 6 7 8 9 10 11 12 13, it would sum them all up to 91 Thanks for the help in advance. import java.util.Scanner; public class test { public static final int SENTINEL = -1; public static void main(String[] args) { Scanner kb = new Scanner(System.in); int score = 0; int sum = 0; System.out.println("Enter numbers here"); while (score >= 0) { if (score <= -1) { score = kb.nextInt(); sum += score; score = 0; } System.out.println(sum); } } } Thanks to libik for all his time and help, here is the finished code. import java.util.Scanner; public class JavaApplication1156 { public static void main(String[] args) { System.out.println("Enter numbers here"); int sum; do { Scanner kb = new Scanner(System.in); int score = 0; sum = 0; String line = kb.nextLine(); kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work. while (kb.hasNextInt()) { score = kb.nextInt(); sum += score; } if (sum <= -1) System.out.println("Application ended"); else if (sum >= 0) System.out.println("Sum = " + sum); } while (sum != -1); } } https://crbtech.in/java-training/top-15-java-interview-questions-that-helps-to-crack-interview/
11th Oct 2018, 10:18 AM
meenal deshpande
0
Thank you alot
11th Oct 2018, 10:47 AM
Uros Ristic