# Help with modularity? Declaring methods and return values

• 02-02-2011, 05:23 AM
hiei_yasha
Help with modularity? Declaring methods and return values
Hi, I was wondering if anyone had any tips/recommendations as to how to make my program more modular. I want several methods for each part of my program.

My program does what I want it to if it's all in main, but once I start making new methods I get confused about how to name the method, what I'm supposed to return, and what to pass in and whatnot. I'm working with arrays and user input. Any help appreciated!

Code:

```//Take 2 sets of numbers from user, and displays the mean of those numbers. //Means displayed in 2 decimal places import java.util.*; //for Scanner import java.text.*; //for DecimalFormat public class ArrayPractice {         public static void main (String [] args)         {                 Scanner kb = new Scanner(System.in);                 DecimalFormat twoDecimals = new DecimalFormat("0.00");                                 System.out.print("Please enter a number, between 1 and 25 (Enter 99 to quit): ");                 int numNums1 = kb.nextInt();                 double [] myArray1 = new double [numNums1];                         if (numNums1 == 99)                         System.exit(99);                                 for (int x = 0; x < myArray1.length; x++)                 {                         System.out.println("Enter that many numbers, from -1,000,000 to 1,000,000");                         myArray1[x] = kb.nextDouble();                 }                                 /////////////////////////////////////////////////////////////////////                                 System.out.print("Please enter a new number, between 1 and 25 (Enter 99 to quit): ");                 int numNums2 = kb.nextInt();                 double [] myArray2 = new double [numNums2];                         if (numNums2 == 99)                                 System.exit(99);                                 for (int x = 0; x < myArray2.length; x++)                 {        System.out.println("Enter that many numbers, from -1,000,000 to 1,000,000");                         myArray2[x] = kb.nextDouble();                 }                                 /////////////////////////////////////////////////////////////////////                                 double sum1 = 0.0;                 for (int x = 0; x < myArray1.length; x++)                 {                         sum1 = sum1+myArray1[x];                 }                 double mean1 = sum1/numNums1;                 System.out.println("Mean of first set" + twoDecimals.format(mean1));                                 /////////////////////////////////////////////////////////////////////                                 double sum2 = 0.0;                 for (int x = 0; x < myArray2.length; x++)                 {                         sum2 = sum2+myArray2[x];                 }                 double mean2 = sum2/numNums2;                 System.out.println("Mean of second set" + twoDecimals.format(mean2));                 }         }```
• 02-02-2011, 05:37 AM
Junky
There is no rule as to how you name a method or what it returns. However the name shouold reflect what it does. So if you write a method to remove a given char from a string then removeChar is a good name while badger is not.

Once again what the method returns depends upon what it is supposed to do.

Looking at your code you can see that you basically have reproduced the code to get create an array and get user input. So that can be moved to a method and you simply call that method twice, once for each array. For example:
Code:

```double[] array1 = aMethodWithABetterName(); double[] array2 = aMethodWithABetterName();```
Hopefully you can decide what the method should return.
• 02-02-2011, 05:52 AM
hiei_yasha
So for example, if I wanted to make a method for finding the mean of the first set..would it look like this?

Code:

```public static void main() {   CalcMean1(_mean1_); } public static double CalcMean1(*) {   enter code here for calculating mean1;   SOP(mean1);   return mean1?; }```
in main, I am confused what I need in the parentheses with underlines, if anything. Anything needed to the left of the method call?
And what is needed in the (*) part?
• 02-02-2011, 06:13 AM
Junky
Quote:

Originally Posted by hiei_yasha
what I need in the parentheses with underlines

Whatever you are trying to calculate the mean of. Do you think you would pass a Fish or maybe a Truck or a Foo?
Quote:

Anything needed to the left of the method call?
It depends. Do you want to store whatever the method returns? Should your method be returning anything?
Quote:

And what is needed in the (*) part?
Just like declaring a variable and it must match whatever you decide to pass the method (as per discussion above).
• 02-02-2011, 06:28 AM
Vase
Here's an example of what it looks like you're trying to do. I'll let you analyze it and see if you can apply it to the rest of your program.

Code:

```public static void main(String[] args) {   double num1 = 4.5, num2 = 2.7;   double mean = calcMean(num1, num2);   System.out.println("The mean of " +         num1 + " and " +         num2 + " is " + mean); } public static double calcMean(double number1, double number2) {   double mean = (number1 * number2) / 2.0;   return mean; }```

The output of this code:
The mean of 4.5 and 2.7 is 1.66666667
• 02-02-2011, 11:23 PM
milovan
These are a few hints how i would solve this:

First I would create a method for informing a user and capturing user input.

I would do this in a method named getArray()

Since this method only captures array of doubles(in your case) you need another method for calculating result.

Let's call this second method result()

And that is basicly all you need.
Now let's explain how these methods should work.

This method will use array of doubles from getArray() for its calculation.
So you can organize your method in next way:
Code:

```public void result(double[] array){ // array is value form [I]getArray()[/I]     // calculation code }```

or even better:
Code:

```public void result(getArray()){     // now method [I]result()[/I] is provided with [I]double[/I] array directly form [I]getArray()[/I]     // you can now make your calculations }```

to acomplish this, method getArray() must have double[] return value and it should looks like:
Code:

``` public double[] getArray(){     // your code for informing a user and capturing numbers from user }```

Good idea is to also have result() to return resulting value so it should looks like:
Code:

```public double result(getArray()){     // calculation code }```

Now populated methods should looks like:
Code:

```public double[] getArray(){     // next is actualy your code            Scanner kb = new Scanner(System.in);     System.out.print("Please enter a number, between 1 and 25 (Enter 99 to quit): ");     int numNums = kb.nextInt();     double [] myArray = new double [numNums];     if (numNums == 99)         System.exit(99);     for (int x = 0; x < myArray.length; x++){         System.out.println("Enter that many numbers, from -1,000,000 to 1,000,000");         myArray[x] = kb.nextDouble();     }     return myArray; // returns [I]double[][/I] }```

and
Code:

```public double result(double[] array){     // again your code            double mean = 0.0;     double sum = 0.0;         for (int x = 0; x < array.length; x++){         sum = sum + array[x];         }         return mean = sum / array.length;     }```

Now you can create some double variable with a value from result:
Code:

```double mean1 = result(getArray()); double mean2 = result(getArray());```

and print this on screen:
Code:

```System.out.println("Mean of first set: " + twoDecimals.format(mean1)); System.out.println("Mean of second set: " + twoDecimals.format(mean2));```

Or, if you don't need resulting vales other than showing result you can avoid alocating memory for mean1 and mean2 in next way:

Code:

``` System.out.println("\nMean of first set: " + twoDecimals.format(result(getArray())) + "\nMean of second set: " + twoDecimals.format(result(getArray())));```

One more thing, if you want to use these methods from main() method you must make them static
or you could avoid this by calling them from constuctor for example.

Finaly complete code is here:
Code:

```import java.util.Scanner; import java.text.DecimalFormat; public class MyTest {             DecimalFormat twoDecimals = new DecimalFormat("0.00");             public MyTest(){         System.out.println("\nMean of first set: " + twoDecimals.format(result(getArray())) + "\nMean of second set: " + twoDecimals.format(result(getArray())));     }     public double[] getArray(){                     Scanner kb = new Scanner(System.in);         System.out.print("Please enter a number, between 1 and 25 (Enter 99 to quit): ");         int numNums = kb.nextInt();         double [] myArray = new double [numNums];         if (numNums == 99)         System.exit(99);             for (int x = 0; x < myArray.length; x++){             System.out.println("Enter that many numbers, from -1,000,000 to 1,000,000");             myArray[x] = kb.nextDouble();             }             return myArray;     }     public double result(double[] array){                     double mean = 0.0;         double sum = 0.0;         for (int x = 0; x < array.length; x++){         sum = sum + array[x];         }         return mean = sum / array.length;     }     public void main(String[] args){         MyTest test = new MyTest();     } }```
I hope this is of any help to you and good luck with java!!!
• 02-03-2011, 12:18 AM
aspire1
General modularity tips: do a search on cohesion, coupling and programming to interfaces.
• 02-03-2011, 02:48 AM
hiei_yasha
Thanks all, that was very helpful. Your program does exactly what I want it to, however, I want to make it my own :)
I need to make more methods and each method static, and want my display portion in main. It makes things longer I know, but part of my task is to make each little step its own method. I think I've done the method creation and returns correctly(?), and I emulated your format, but my main still has something wrong. I'm probably missing something simple that I'm overlooking *fingers crossed*:

Code:

```import java.util.Scanner; import java.text.DecimalFormat; public class MeanTest {         public static void main (String [] args)         {                 userPrompt1();                 double mean1 = meanCalc1(fillArray1());                 userPrompt2();                 double mean2 = meanCalc2(fillArray2());                 System.out.print(mean1);                 System.out.print(mean2);         }                 //Prompt for first number         public static int userPrompt1()         {                 Scanner kb = new Scanner(System.in);                 System.out.print("Please enter num of nums: ");                 int numNums1 = kb.nextInt();                         if (numNums1 == 99)                         System.exit(99);                 return numNums1;         }                 //Prompt for numbers to go into first set         public static double [] fillArray1(int numNums1)         {                 Scanner kb = new Scanner(System.in);                 double [] myArray1 = new double[numNums1];                 for (int x = 0; x < myArray1.length; x++)                 {                         System.out.println("Enter that many nums: ");                         myArray1[x] = kb.nextDouble();                 }                 return myArray1;         }                 //Find the mean of first set         public static double meanCalc1(double[]myArray1)         {                 double mean1 = 0.0;                 double sum1 = 0.0;                 for (int x = 0; x < myArray1.length; x++)                 {                         sum1 = sum1 + myArray1[x];                 }                 return mean1 = sum1/myArray1.length;         }                 //Prompt for second number         public static int userPrompt2()         {                 Scanner kb = new Scanner(System.in);                 System.out.print("Please enter num of nums: ");                 int numNums2 = kb.nextInt();                         if (numNums2 == 99)                         System.exit(99);                 return numNums2;         }                 //Prompt for numbers to go into second set         public static double [] fillArray2(int numNums2)         {                 Scanner kb = new Scanner(System.in);                 double [] myArray2 = new double[numNums2];                 for (int x = 0; x < myArray2.length; x++)                 {                         System.out.println("Enter that many nums: ");                         myArray2[x] = kb.nextDouble();                 }                 return myArray2;         }                 //Find the mean of second set         public static double meanCalc2(double[]myArray2)         {                 double mean2 = 0.0;                 double sum2 = 0.0;                 for (int x = 0; x < myArray2.length; x++)                 {                         sum2 = sum2 + myArray2[x];                 }                 return mean2 = sum2/myArray2.length;         } }```
• 02-03-2011, 02:56 AM
Junky
Quote:

Originally Posted by hiei_yasha
but my main still has something wrong.

• 02-03-2011, 03:16 AM
hiei_yasha
well i get a compile error that says: 'fillArray1(int)' cannot be applied to ().
double mean1 = meanCalc1(fillArray1());
and the same for fillArray2().

so, I tried putting in mean1, numNums1, double[]myArray1, switching fillArray1 and meanCalc1, but end up getting similar compile errors.
• 02-03-2011, 03:27 AM
Junky
Programming doesn't happen by guessing. You need to understand and not just wild throw stuff at the compiler and hope it is correct.

You are calling the fillArray1 method and passing in no parameters. How many and what type of parameters does that method want?

Also you have a fillArray1 and fillArray2 method which do the exact same thing. You only need one method. Same for meanCalc1 and meanCalc2.
• 02-03-2011, 03:42 AM
hiei_yasha
Got it. I had tried using numNums but hadn't initialized it correctly to the userPrompt.

Code:

```public static void main (String [] args)         {                 DecimalFormat twoDec = new DecimalFormat("0.00");                 int numNums1=userPrompt1();                 double mean1 = meanCalc1(fillArray1(numNums1));                 int numNums2=userPrompt2();                 double mean2 = meanCalc2(fillArray2(numNums2));                 System.out.println("Mean " + twoDec.format(mean1));                 System.out.println("Mean " + twoDec.format(mean2));         }```
Quote:

Originally Posted by Junky
Also you have a fillArray1 and fillArray2 method which do the exact same thing. You only need one method. Same for meanCalc1 and meanCalc2.

I know, like I said, it's redundant, but our teacher basically wants us to have two sets of methods, one for each collection of numbers and means and whatnot :/ I think his intention was practice rather than conciseness at this point.

Again, thanks all. My program (even though it looks hideous, by instruction) does what I want it to :)