0

I am trying to find the average number of students per class but when I test my program, it only prints 1 or 0 everytime. Any help would be appreciated.

import java.util.Scanner;
 public class Test {

public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the number of Students: ");
int s = reader.nextInt();
System.out.println("Please enter the number of classes: ");
int c = reader.nextInt();
int numbStud1 = 0;
int numbClass1 = 0;
double averages =calcAverage (numbStud1 + c,numbClass1 + s) ;
System.out.println("The average is: "  + averages);
}
public static double calcAverage(int numbStud, int numbClass){
    double average1;
    average1 = numbStud  /  numbClass;
    return average1;
}

}

Sergio
  • 21
  • 5
  • `numbStud / numbClass` - int divided by int is still int. The value is converted to double when it is being assigned to `average1`, but the actual calculation already took place. – Jaroslaw Pawlak Feb 22 '16 at 20:31
  • change `average1 = numbStud / numbClass;` to `average1 = (numbStud * 1.0) / numbClass;` – Atri Feb 22 '16 at 20:31
  • I think my average1 = numbStud / numbClass is not the right calculation needed. Because now when I enter 30 students then enter 15 classes, my answer is 2 students per class which is not right. – Sergio Feb 22 '16 at 20:33
  • Ah, yes I saw that right when I posted my question Thanks for pointing out! As I mentioned earlier when I enter 30 for students then 15 for number of classes, I get 2 students per class which is way off lol – Sergio Feb 22 '16 at 20:36

1 Answers1

0

The issue is this:

  double averages =calcAverage (numbStud1 + c,numbClass1 + s) ;

Replace it with exchanging c with s:

  double averages =calcAverage (numbStud1 + s,numbClass1 + c) ;

And if you want avrage more precision use :

  average1 = (numbStud*1.0 / numbClass*1.0);
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
  • Yep! That definitely gave me different outputs, but my answer doesn't seem right. When I enter 30 students then enter 15 classes, my answer is 2 students per class which is wrong. Is there something missing in my calculations. – Sergio Feb 22 '16 at 20:42
  • 30 students , 15 classes gives 2 is right @Sergio – Abdelhak Feb 22 '16 at 20:44
  • Oh my gosh! your so right. I had a brain fart moment there. Thank you so much, helped clear so many things for me – Sergio Feb 22 '16 at 20:51