Simple Averaging Program
by
, January 29th, 2012 at 04:56 PM (1887 Views)
What this application does is collects a number of inputs from the user via a scanner. These inputs are numbers. They are then averaged and the average is outputted. Pretty simple stuff.
import java.util.Scanner; class Class1{ public static void main(String args[]){ Scanner input = new Scanner(System.in); int total = 0; int grade; int average; int counter = 0; int numGrades = 10; System.out.println("Please enter " + numGrades + " numbers to be averaged"); while(counter < numGrades){ grade = input.nextInt(); total = total + grade; counter++; } average = total/numGrades; System.out.println("Your average is " + average + "."); } }
How could I change this to make it more challenging to create? I could have used multiple classes or multiple methods to do various tasks. For example, one method could be used to loop through the inputs, and another could be used to find the average. In fact, I'm going to do this now. Check it out.
import java.util.Scanner; class Class1{ public static void main(String args[]){ int numGrades = 10; System.out.println("Please enter " + numGrades + " numbers to be averaged"); //Start loop/average method Class1 class1Object = new Class1(); class1Object.loopAverage(numGrades); } public void loopAverage(int numGrades){ int grade; int counter = 0; int total = 0; int average; Scanner input = new Scanner(System.in); while(counter < numGrades){ grade = input.nextInt(); total = total + grade; counter++; } average = total/numGrades; System.out.println("Your average is " + average + "."); } }
I managed to use the main method for the introduction and to call the second method. I tried using three methods, one for the main method, one for the loop, and one for the average, however, when I tried sending variables from the loop method to the average method, it was reading the variables from the main method. I wasn't sure how to go about fixing this, so if anyone could help out, I'd really appreciate that. I'll look into it myself now.
Maybe I could use something like this.
public String getTotal(){ return total; }
But then how would this know to get the total from the loop method and not the main method? And I want to send the total from the loop method and the numGrades from the main method? Not sure how to go about doing this.