BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String sNum = reader.readLine();
int sum = 0;
while (true) {
int num = Integer.parseInt(sNum);
sum += num;
if (num == -1) {
break;
}
}
System.out.println(sum);
}
}
This is my logic towards the solution of the task and yet when compiled should work properly but instead kept on looping again and again
Under discussion
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
5 January, 14:45
What are the task conditions and requirements? How does the logic of this code work towards reaching those conditions and requirements? What do you think is the problem that is preventing the code from being validated?
0
whoseunassailable Backend Developer
6 January, 07:44
i just needed to display addition of n elements and then stop when input is equal to -1.The thing here is if i use reader.readLine() directly instead of declaring the variable sNum, then the code works and that's the reason why i don't understand why this doesn't work.
0
Lisa
6 January, 10:00
If you readLine() 'directly' in line 5 as argument for parseInt(), then you read a new value in each iteration of the loop.
If you read a string value (once) outside the loop (as you do now), that value won't change inside the loop. To have the same behavior you'd need to move line 2 inside the loop, between lines 4 and 5.
+2
whoseunassailable Backend Developer
7 January, 08:36
Ohhhhhh i see. Well for a beginner like me it's confusing a bit but i understood. Hope i won't make the same mistake again and again in the near future.
+1