public class Solution {
public static void main(String[] args) throws Exception {
//write your code here
boolean t = true;
while(t=true){
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String s = r.readLine();
int a = Integer.parseInt(s);
int m=0;
m=m+a;
int n = 0;
if(a==(-1)){
double d = m/n;
System.out.println(d);
t = false;
}
n++;
}
}
}
whats the error
Under discussion
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Emil Valentin Toma
7 March 2019, 17:19
Hi Harinath,
If you type in -1 as the first number, so that you want to end app before actually doing any average, wouldn't that lead to m being divided by 0? That's because it jumps straight to
...while n is still 0, remember initialization? n++ is coming too late and the program won't even get that far. Disclaimer: I didn't run the code, just saw it, so my comment must be taken with pinch of salt please.
Please fix this and let us know what other errors are there. And shouldn't you initialize n outside the while loop? Otherwise the increment inside the while loop scope will be reset to zero at the beginning of each loop. 0
Khurram
5 March 2019, 09:57
= is the assignment operation, you can assign values to variables with it
== is the equality operator, you can test whether a variable is equal to another or not
in the while loop condition, you need to check (t == true) not (t = true)
better yet just enter while (t) , the condition is evaluated to true or false and then the loop either executes or stops
if t = true, while (t) evaluates to while (true) and continues looping
and if t = false, while (t) will evaluate to while (false) and stop looping
0
Harinath Reddy A
5 March 2019, 10:08
but yet the error is something different it is related to the bufferedreader.
0
Khurram
8 March 2019, 17:11
apart from that, 2 more errors are
1) int a = Integer.parseInt(s); // user input is stored in a
int m=0; // new variable m is created and 0 is assigned to it
m=m+a; // 0+a is stored in m
now the 2nd time the loop runs, int m = 0 will execute again, it will make m = 0 and your previous addition will be lost.
2) same thing with int n = 0, you are increasing n by 1 each time the loop runs, but you are also making it 0 again in the loop, so when you perform double d = m/n, this is basically doing a division by 0 operation and the program crashes.
0