public class StampaInversa {
private static class NumberWithCounterAndAverage{
private int number=0;
private int counter=1;
private int average=0;
public int getNumber(){
return number;
}
public int getCounter(){
return counter;
}
public void setNumber(int number){
this.number=number;
}
public void setCounter(int counter){
this.counter+=counter;
}
public int getAverage(){
return avrage;
}
public void setAverage(int average){
this.average=average;
}
public String toString(){
return "Number: "+number+"Counter "+counter+"Average "+average;
}//toString
}//NumeroConContatore
public static void reversePrint(){
Scanner sc= new Scanner(System.in);
System.out.println("Insert number");
int x=sc.nextInt();
if(x==0) return;
reverseprint();
System.out.println(x);
}
public static int sumPrint(){
Scanner sc=new Scanner(System.in);
System.out.println("Insert number");
int x=sc.nextInt();
if(x!=0) x+=sumPrint();
return x;
}
public static NumberWithCounterAndAverage printAverage(){
Scanner sc=new Scanner(System.in);
NumberWithCounterAndAverage ncc= new NumberWithCounterAndAverage();
System.out.println("Insert number");
int x=sc.nextInt();
if(x!=0){
NumberWithCounterAndAverage nccem= printAverage();
ncc.setNumber(x+nccem.getNumber());
ncc.setCounter(+nccem.getCounter());
}
if (x!=0){
ncc.setAverage(ncc.getNumber()/(ncc.getCounter()-1));
}
return ncc;
}
public static void main(String[] args) {
NumberWithCounterAndAverage nccem= printAverage();
System.out.println(nccem.getCounter()+" "+nccem.getNumber()+" average "+nccem.getAverage());
}
}//StampaInversa
My prof. gave me an assignment: write tail recursive functions to calculate:
the sum of the number inserted from input till 0 is inserted;
the average of the number inserted till 0 is inserted;
the standard deviation of the number inserted till 0 is inserted;
The conditions to accomplish the assignment are:
No data structure allowed (arrays, arraryslist, LinkedList...), only ad hoc objects are allowed (such as the one that I have created: NumberWithCounterAndAverage)
No istance variables allowed, the variables must be own only by the functions.
The function must be recursive.
The functions in the code above work perfectly, but now I need to made a recursive function to calculate the standard deviation with the condition descripted above. Do you have any clue?
If it is still not clear how the function should be, tell me.