package com.codegym.task.task05.task0507;
/*
Arithmetic mean
*/
import java.io.*;
public class Solution {
public static void main(String[] args) throws Exception {
//write your code here
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
float mean = 0;
float sum = 0;
float counter = 0;
while (true){
String input = reader.readLine();
float number = Float.parseFloat(input);
if (number==-1){
break;
}
else if (number<0 || number>0){
sum = sum+number;
counter++;
}
}
mean = sum/counter;
System.out.println(mean);
}
}
Why is my code failing the last part of verification? Everything checks out but " The displayed result should match the task conditions for any input data. " Please help :(
Resolved
Comments (9)
- Popular
- New
- Old
You must be signed in to leave a comment
Hryniup
19 May 2019, 11:24solution
What about this case?
If you sequentially enter the numbers -100, 0, 100, and -1, the program should display 0.0.
Ur else if statement is unnecessary imho.
+4
John Michael Montuya
19 May 2019, 14:33
Ironically the unnecessary else if statement was the cause, so you are spot on! My logic was for the program to break if non-integers were entered but its actually pretty pointless :P
I removed all the unnecessary crap and got it to work.
0
romeo
2 June 2019, 21:16
So how did you get the program to add the inputs together without if else?
like this?
else if (number != -1){
}
0
John Michael Montuya
2 June 2019, 21:24
Just removed the extra "if" and left it as "else", not "else if":
if (number==-1){
break;
}
else {
sum = sum+number;
counter++;
}
+2
Joseph
17 July 2019, 04:22
I've been having a problem with this and the similar adding task from before. If I declare and initialize any variables in main and then have a while loop in main the while loop will not use them. Then it doesn't output the value of "mean" outside the while loop. I've tried working the code how you have it (including the corrections) and it still doesn't work.
0
John Michael Montuya
17 July 2019, 17:15
can you paste your code here?
0
Joseph
17 July 2019, 21:29
Looks like I was wrong. The task verified and I passed it. For one I didn't think about the fact that it only displays after the while loop breaks, and that only happens when I input -1. The other reason was when doing the task on the site I was having trouble compiling it. It kept giving me an error on the line where I parseFloat inside the while loop. But on the ide I had no problem with that at all. Still not sure why that is.
0
John Michael Montuya
17 July 2019, 21:50
Good stuff! The web IDE is actually wonky sometimes, so I recommend that you use IDEA for more complex tasks moving forward.
0
Joseph
17 July 2019, 22:25
It does seem that way. Might have been my fault but who knows. Thanks for the reply!
0