Try this(much coded but it works for any number of input):
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 0;
String line;
ArrayList<Integer> total = new ArrayList<>();
boolean isNext = true;
System.out.println("Input a value or 'e' to exit:");
do{
try{
line = scan.nextLine();
String num[] = line.split("\\s+");
int sum = 0;
for(String a : num){
//if entered value equal to character 'e' print done and sum
if(a.equals("e")){
a = a.replace("e", "0");
sum += Integer.parseInt(a);
isNext = false;
System.out.println("Done!");
}else{
sum += Integer.parseInt(a);
}
}
total.add(sum);
}catch(NumberFormatException e){
System.out.println("Wrong input!");
}
count++;
}while(isNext);
for(Integer i: total){
System.out.println(i);
}
}
Output:
Input a value or 'e' to exit:
10 20
1 2 3 4 5 6
10 -20 50 -90 e
Done!
30
21
-50
UPDATE:
Above program is my own one that added according to your question before you update it. In your update you have added your program that you tried. And your updated question is:
there's no output. (3 means the user will key in 3 lines of integers)
When you run your program there is no errors it is running, you cannot see terminal or if IDE console it is asking for a input.
You can add numbers but loop never stop(infinite) even if you add for a three lines.
The reason is while
loop:
while(input.hasNext()){
total += input.nextInt();
}
Once program hits the while
loop it is never going back to for loop. Because the condition hasNext()
check for next input and it alsways has(return true
).
Another way I can explain it is, compiler look for next token from input and can still collect input while there is input to be collected inside the loop, while that is true, it keeps doing so.
Solution:
If you can keep variable for special character or word("exit") to end loop it is good. But as a solution for your code, you can declare a variable and increment it in each iteration untill it getting equal to your first input number.
Code should look like this:
Scanner input = new Scanner(System.in);
int k = input.nextInt();
int total = 0;
int count = 0;
while(count != k && input.hasNext()){
count++;
total += input.nextInt();
}
System.out.println(total);
This will get only one line. To get more lines try my program above. And read this to learn more about hasnext()
.