# Not sure how to logically correct a method.

• June 25th, 2012, 10:22 PM
orbin
Not sure how to logically correct a method.
I'm creating a class and methods and calling them in the main method. It's to find avg/median/total etc etc of an array.

Code :

```import java.util.Arrays;     public class ArrayOps1D {       public static int getTotal(int[] scores) {   int total = 0;   for(int j = 0; j <scores.length; j++) {   total = total + scores[j];       }   return total;       }     public static int getAverage(int[] scores){ int total = 0; int average = 0;   for(int i = 0; i < scores.length; i++) { total += scores[i]; average = (total / scores.length);   }   return average;     }   public static int getLowest(int[] scores) {   int lowest = 100;   for(int i = 0; i < scores.length; i++) {     if (scores[i] < lowest)   { lowest = scores[i];   }   }   return lowest; }     public static int getHighest(int[] scores) { int highest = 0;   for(int i = 0; i < scores.length; i++)   { if(scores[i] > highest) { highest = scores[i];   }     } return highest;   }     public static int getMedian(int[] scores) {   int median = 0;   Arrays.sort(scores);     int middle = (scores.length / 2);   if ( 0 == scores.length % 2)   median = (scores[middle] + scores[middle+1])/2;   else if (0 != scores.length % 2) { median = scores[middle];   } return median; }   public static int getPosition(int[]scores, int number) { int holder = 0;   for (int i = 0; i < scores.length; i++) { if(number == scores[i]) {   holder = i; }   } return holder; } }```

and also this...

Code :

```import java.io.*; import java.util.Arrays;     public class staticMethods{   public static void main(String[] args) throws IOException{   File dataFile = new File("G:\\COSC 1337\\Homework\\Static Methods HW\\Scores.txt"); BufferedReader br = new BufferedReader(new FileReader(dataFile));   String scoresString = new String(); String[] scoresArray = new String[36]; int[] scoresIntArray = new int[36];   scoresString = br.readLine(); scoresArray = scoresString.split(" ");   for(int i = 0; i < scoresArray.length; i++) {   scoresIntArray[i] = Integer.parseInt(scoresArray[i]);   }   String displayRows = new String(); for(int i = 0; i < scoresIntArray.length; i++) { displayRows += scoresIntArray[i++] + " " + scoresIntArray[i++] + " " + scoresIntArray[i++] + " " + scoresIntArray[i] + "\n";   } System.out.println(displayRows);       br.close();   System.out.println("The total of the array is " + ArrayOps1D.getTotal(scoresIntArray) + "."); System.out.println("The average of the array is " + ArrayOps1D.getAverage(scoresIntArray) + "."); System.out.println("The lowest number of the array is " + ArrayOps1D.getLowest(scoresIntArray) + "."); System.out.println("The highest number of the array is " + ArrayOps1D.getHighest(scoresIntArray) + "."); System.out.println("The median of the array is " + ArrayOps1D.getMedian(scoresIntArray) + "."); System.out.println("The position of the number in the array is " + ArrayOps1D.getPosition(scoresIntArray,68)); System.out.println("The position of the number in the array is " + ArrayOps1D.getPosition(scoresIntArray,77)); System.out.println("The position of the number in the array is " + ArrayOps1D.getPosition(scoresIntArray,99)); } }```

What I'm having trouble with is when I call the method get position, it needs to find the position of the number you are checking for. Two numbers (68 and 99) work fine because they exist in the scores array, but 77 does not. I'm trying to figure out a way to display a message saying this number does not exist within the array, but am having trouble logically figuring it out. It feels like there is a really simple solution but for some reason I can't figure it out.
• June 25th, 2012, 10:38 PM
pbrockway2
Re: Not sure how to logically correct a method.
Code :

``` /** * Comment needed here! */ public static int getPosition(int[]scores, int number) { int holder = 0;   for (int i = 0; i < scores.length; i++) { if(number == scores[i]) {   holder = i; }   } return holder; }```

So what is the method supposed to do? I mean in detail (and covering every possible case) what is it supposed to do? I'm a fan of documentation: it helps someone reading the code know what is intended, and it helps you answer the question you have posed. Basically once you have a clear idea of what the method should do (so that you can later use that behaviour in the other class), then you can start writing/testing the code.

The String class has an indexOf() method that does something a bit similar. What the writers of that method decided was that it should return -1 if the thing being searched for wasn't there. That's because there's no way -1 could ever be a "real" index position. It's often a good idea to steal other people's ideas: they are pretty clever and experienced and (more subtly) other Java users will recognise the "idiom" if it resembles what they are used to elsewhere.

In any case, whatever you decide to do, document it. "Returns the position of a given value in a given array. If the value is not present ..." And if you have trouble implementing it as code, post what you're thinking.
• June 25th, 2012, 10:41 PM
pbrockway2
Re: Not sure how to logically correct a method.
And another thing the documentation should clear up: what is the method supposed to return when a value occurs multiple times within an array?
• June 25th, 2012, 11:10 PM
orbin
Re: Not sure how to logically correct a method.
The way my teacher described it is vague, but I will do my best. We are supposed to create a method, so that when they search for a number for example let's say 68. If 68 exists in the array, please return what position(or element) it exists in the array. If it does not exist, write a line saying that it does not exist. It does not cover if it finds it multiple times.

Also another issue I'm having is writing a file Deviations.txt to my computer. I'm supposed to find deviations from the average of the numbers of the array, which I did, but having trouble actually using FileWriter to output a Deviations.txt

Code :

```import java.util.Arrays; import java.io.*;     public class ArrayOps1D{       public static int getTotal(int[] scores) {   int total = 0;   for(int j = 0; j <scores.length; j++) {   total = total + scores[j];       }   return total;       }     public static int getAverage(int[] scores){ int total = 0; int average = 0;   for(int i = 0; i < scores.length; i++) { total += scores[i]; average = (total / scores.length);   }   return average;     }   public static int getLowest(int[] scores) {   int lowest = 100;   for(int i = 0; i < scores.length; i++) {     if (scores[i] < lowest)   { lowest = scores[i];   }   }   return lowest; }     public static int getHighest(int[] scores) { int highest = 0;   for(int i = 0; i < scores.length; i++)   { if(scores[i] > highest) { highest = scores[i];   }     } return highest;   }     public static int getMedian(int[] scores) {   int median = 0;   Arrays.sort(scores);     int middle = (scores.length / 2);   if ( 0 == scores.length % 2)   median = (scores[middle] + scores[middle+1])/2;   else if (0 != scores.length % 2) { median = scores[middle];   } return median; }   public static int getPosition(int[]scores, int number) { int holder = 0;   for (int i = 0; i < scores.length; i++) { if(number == scores[i]) {   holder = i; }   } return holder; }     public static int[] getDeviation(int[] scores) { int[] tempArray = new int[scores.length]; int[] deviations = new int[scores.length];   for(int i = 0; i < scores.length; i++) {   tempArray[i] = scores[i]; deviations[i] = ((scores[i] - getAverage(scores)) * (scores[i] - getAverage(scores))); }   PrintWriter outputFile = new PrintWriter("C:\\Deviations.txt");   for(int i = 0; i < scores.length; i++) { outputFile.println(deviations[i]);     } outputFile.close();     return deviations;   } }```

Code :

```import java.io.*; import java.util.Arrays;     public class staticMethods{   public static void main(String[] args) throws IOException, FileNotFoundException{   File dataFile = new File("G:\\COSC 1337\\Homework\\Static Methods HW\\Scores.txt"); BufferedReader br = new BufferedReader(new FileReader(dataFile));   String scoresString = new String(); String[] scoresArray = new String[36]; int[] scoresIntArray = new int[36];   scoresString = br.readLine(); scoresArray = scoresString.split(" ");   for(int i = 0; i < scoresArray.length; i++) {   scoresIntArray[i] = Integer.parseInt(scoresArray[i]);   }   String displayRows = new String(); for(int i = 0; i < scoresIntArray.length; i++) { displayRows += scoresIntArray[i++] + " " + scoresIntArray[i++] + " " + scoresIntArray[i++] + " " + scoresIntArray[i] + "\n";   } System.out.println(displayRows);       br.close();   System.out.println("The total of the array is " + ArrayOps1D.getTotal(scoresIntArray) + "."); System.out.println("The average of the array is " + ArrayOps1D.getAverage(scoresIntArray) + "."); System.out.println("The lowest number of the array is " + ArrayOps1D.getLowest(scoresIntArray) + "."); System.out.println("The highest number of the array is " + ArrayOps1D.getHighest(scoresIntArray) + "."); System.out.println("The median of the array is " + ArrayOps1D.getMedian(scoresIntArray) + "."); System.out.println("The position of the number in the array is " + ArrayOps1D.getPosition(scoresIntArray,68)); System.out.println("The position of the number in the array is " + ArrayOps1D.getPosition(scoresIntArray,77)); System.out.println("The position of the number in the array is " + ArrayOps1D.getPosition(scoresIntArray,99)); } }```

I'm getting the output of a filenotfoundexception poiting at the FileWriter line.
• June 25th, 2012, 11:49 PM
pbrockway2
Re: Not sure how to logically correct a method.
Quote:

We are supposed to create a method, so that when they search for a number for example let's say 68. If 68 exists in the array, please return what position(or element) it exists in the array. If it does not exist, write a line saying that it does not exist.
It's a method in the other class that will "write a line saying that it does not exist". As far as the ArrayOps1D class is concerned you need to decide what the getPosition() method is going to return when the target value is missing. You are free to have it return anything you like, but it must return something (because its declared to return an int) and you should have it return a value that will be useful to the caller.

Quote:

I'm getting the output of a filenotfoundexception poiting at the FileWriter line.
Do you mean the PrintWriter line, "PrintWriter outputFile = new PrintWriter("C:\\Deviations.txt");"? According to the API docs you will get that when "the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file". So check that you have the correct permissions to write to the top of the C:\ drive and that the file Deviations.txt does not already exist when you run the program (it might be locked in some way).

Nothing in the code you posted seems to actually call getDeviation(), so it's a bit hypothetical at the moment.
• June 26th, 2012, 02:09 PM
orbin
Re: Not sure how to logically correct a method.
I figured out the getPosition method... but still having trouble with PrintWriter. I made sure that the file is not read only and it is in the right location. I'm not 100% sure but am I supposed to have the text file already created called Deviations or does it create it itself?

Code :

```import java.util.Arrays; import java.io.*;     public class ArrayOps1D{       public static int getTotal(int[] scores) {   int total = 0;   for(int j = 0; j <scores.length; j++) {   total = total + scores[j];       }   return total;       }     public static int getAverage(int[] scores){ int total = 0; int average = 0;   for(int i = 0; i < scores.length; i++) { total += scores[i]; average = (total / scores.length);   }   return average;     }   public static int getLowest(int[] scores) {   int lowest = 100;   for(int i = 0; i < scores.length; i++) {     if (scores[i] < lowest)   { lowest = scores[i];   }   }   return lowest; }     public static int getHighest(int[] scores) { int highest = 0;   for(int i = 0; i < scores.length; i++)   { if(scores[i] > highest) { highest = scores[i];   }     } return highest;   }     public static int getMedian(int[] scores) {   int median = 0;   Arrays.sort(scores);     int middle = (scores.length / 2);   if ( 0 == scores.length % 2)   median = (scores[middle] + scores[middle+1])/2;   else if (0 != scores.length % 2) { median = scores[middle];   } return median; }   public static String getPosition(int[]scores, int number) { int indexNumber = 0; for(int i = 0; i < scores.length; i++) { if(number == scores[i]) indexNumber = i; }   if(indexNumber != 0)   return "The position of " + number + " within the array is " + indexNumber + ".";   else return "The number " + number + " you are looking for does not exist in this array.";     }     /*public static int[] getDeviation(int[] scores) { int[] tempArray = new int[scores.length]; int[] deviations = new int[scores.length];   for(int i = 0; i < scores.length; i++) {   tempArray[i] = scores[i]; deviations[i] = ((scores[i] - getAverage(scores)) * (scores[i] - getAverage(scores))); }   PrintWriter outputFile = new PrintWriter("C:\\Deviations.txt");   for(int i = 0; i < scores.length; i++) { outputFile.println(deviations[i]);     } outputFile.close();     return deviations;   }*/ }```

This is the output when I try to build my class, and when I uncomment it. I haven't called deviations method yet, because i want to figure out this error first before moving onto the main method.

Code :

`unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown`
• June 26th, 2012, 04:22 PM
kindk12
code is corrected
I HAVE NOT SEEN YOU OTHER CLASSES AND FUNCTIONS BUT AS FAR AS I SAW YOUR LAST CLASS, I CORRECTED SOME STUFF THAT WILL GIVE YOU CORRECT RESULT.
THE OLD ONES ARE COMMENTED AND THE I HAVE ADDED THE NEWER ONES. CHECK IT OUT YOURSELF

Code :

```import java.util.Arrays; import java.io.*;   public class ArrayOps1D{   public static int getTotal(int[] scores) { int total = 0;   for(int j = 0; j < scores.length; j++) { total = total + scores[j]; }   return total; }     public static int getAverage(int[] scores) { int total = 0; int average = 0;   for(int i = 0; i < scores.length; i++) { total += scores[i]; //average = (total / scores.length); YOU DONT DO THIS BECAUSE IT CALCULATES THE AVERAGE EVERY TIME WHERE AS WE NEED TO CALCULATE AVERAGE ONLY ONCE. //SO I OMMITTED THIS OUT OF THE LOOP } average = (total / scores.length); //KEEP IT OUTSIDE THE LOOP   return average; }   public static int getLowest(int[] scores) {   //int lowest = 100; YOU ALSO DONT DO THIS BUT INSTEAD SET THE FIRST NUMBER AS THE LOWEST NUMBER AND TEST THE REST OF THE NUMBER WITH IT. int lowest = scores[0]; //SET THE FIRST NUMBER AS THE LOWEST NUMBER AND TEST THE REMAINING WITH IT   for(int i = 0; i < scores.length; i++) { if (scores[i] < lowest) lowest = scores[i]; } return lowest; }     public static int getHighest(int[] scores) { //int highest = 0; YOU DON'T DO THE SAME HERE BUT INSTEAD SET THE FIRST NUMBER AS HIGHEST AND TEST THE REMAIMING WITH IT int highest = scores[0]; //SET THE FIRST NUMBER WITH IT AND TEST THE REMAINING WITH IT   for(int i = 0; i < scores.length; i++)   { if(scores[i] > highest) highest = scores[i];   } return highest;   }     public static int getMedian(int[] scores) {   int median = 0;   Arrays.sort(scores);     int middle = (scores.length / 2);   if (scores.length % 2 == 0) median = (scores[middle] + scores[middle+1])/2; else //ITS OPTIONAL, IT KEEP THE CODE SIMPLE. median = scores[middle];   return median; }   public static String getPosition(int[]scores, int number) { int indexNumber = 0; boolean found = false; //YOU USED BOOLEAN VALUE TO TEST IF THE VALUE HAS BEEN FOUND //THE WAY YOU DID WILL SAY THE NUMBER IS NOT IN ARRAY IF THE NUMBER IS AT THE BEGINNING OF THE ARRAY AT POSITION 0 for(int i = 0; i < scores.length; i++) { if(number == scores[i]) {indexNumber = i; found = true; //IF THE NUMBER IS FOUND IT SETS TO TRUE OR ELSE TO FALSE } }   //if(indexNumber != 0) YOU DONT DO THIS BECAUSE WHAT IF THE NUMBER YOU ARE SEARCHING IS AT THE BEGINNING OF THE ARRAY THEN THE ELSE STATEMENT WILL RETURN if(found == true) return "The position of " + number + " within the array is " + indexNumber + "."; else return "The number " + number + " you are looking for does not exist in this array."; }     public static int[] getDeviation(int[] scores) throws IOException { int[] tempArray = new int[scores.length]; int[] deviations = new int[scores.length]; int average = getAverage(scores); //CALCULATE AVERAGE ONLY ONCE   for(int i = 0; i < scores.length; i++) {   tempArray[i] = scores[i]; //deviations[i] = ((scores[i] - getAverage(scores)) * (scores[i] - getAverage(scores))); //THOUGH IT WORKS BUT YOU SEE YOU ARE CALCULATING THE AVERAGE EVERY TIME, WHICH IS REQUIRED AND TO CALCULATE SQUARE ROOT JUST USE MATH.SQRT() deviations[i] = (int)Math.sqrt(scores[i] - average); //YOU DONT HAVE TO CALCULATE AVERAGE EVERY TIME, JUST ONE TIME IS ENOUGH. (int) is just there to convert the double to integer }   PrintWriter outputFile = new PrintWriter("Deviations.txt"); //UNLESS STATED YOU CAN JUST USE THE FILE NAME. IT WILL BE SAVE IN THE SAME FOLDER YOU SAVED YOU PROGRAM   for(int i = 0; i < scores.length; i++) { outputFile.println(deviations[i]);   } outputFile.close();     return deviations;   } }```
• June 26th, 2012, 08:47 PM
pbrockway2
Re: Not sure how to logically correct a method.
For most exceptions you must either catch them or have the method specify that they might be thrown. See, eg, The Catch or Specify Requirement in Oracle's Tutorial.

(Like the behaviour of the position method, this - whether you catch or specify - is not something that is determined by the assignment you were given: rather you decide what you want to do and then ought to document your decision as part of the behaviour of the method.)