0

How to avoid overriding?

Hallo guys, I have written a programm in which I want to store points in an array by using a methode. My code: //created an object Student s1=new Student(); //calling the method inputPoints s1.inputPoints(3); s1.inputPoints(1); public class{ int counter; int[]n; int average; int sum; public float inputPoints(int p) { counter++; n=new int[counter]; for(int i=0;i<counter;i++) { n[i]=note; } for(int i=0;i<counter;i++) { sum+=n[i]; } average=average/counter; return average; } I am getting as an input 2.5, but the average should be 2.0. How can I solve this problem without using ArrayList?

31st Aug 2019, 7:03 AM
Preet
3 Answers
+ 2
https://code.sololearn.com/cRlpJAFT6IfF/?ref=app output = 2.0 because 5/2=2 change datatype variable sum int to float.
31st Aug 2019, 8:40 AM
Prathvi
Prathvi - avatar
+ 1
Share the Code
31st Aug 2019, 7:14 AM
Prathvi
Prathvi - avatar
0
public class Student { public int counter; public int sum; public float average; public int[]n; public float inputPoints(int point) { counter++; n=new int[counter]; //storing the points in the array n for(int i=0;i<counter;i++) { n[i]=point; } //calculating the sum for(int i=0;i<counter;i++) { sum+=n[i]; } average=sum/counter; return average; } public String toString() { return "Average: "+average; } public static void main(String[] args) { Student s1=new Student(); s1.inputPoints(3); s1.inputPoints(1); s1.inputPoints(2); System.out.println(s1); } }
31st Aug 2019, 8:18 AM
Preet