Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 A Loop program
Index -> Programming, Java -> Java Help
Goto page Previous  1, 2
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Mon Apr 05, 2004 9:27 pm   Post subject: (No subject)

Analysis

Well, first let's analyze the problem.

You need to take two pieces of data (the person's name, and their grade) and output a string containing both values, separated by enough characters (either "." or something else, perhaps).

So we want a function... a black box we push data into, and take information out of. What we put in is a name and a grade, and we get out a string.

code:
String getFormattedString(String name, int grade) {

}


That's just a shell, but when it comes to using the function, that's all we'll need to know. Of course, for it to be useful, you need something between the brackets.

This is what you're asking about. So first we need to figure out the length of the name and the length of the grade (it's probably between 0 and 100, so it might be 1 or 3 printed characters).

code:
String getFormattedString(String name, int grade) {
   int nameLen = name.length();
   int gradeLen;

   if (grade < 10)
      gradeLen = 1;
   else if (grade < 100)
      gradeLen = 2;
   else
      gradeLen = 3;
}


So now we know how how much of those 30 characters the two pieces of data will take up in the end result. Thus we can figure out the number of dots we'll need.

code:
String getFormattedString(String name, int grade) {
   int nameLen = name.length();
   int gradeLen;

   if (grade < 10)
      gradeLen = 1;
   else if (grade < 100)
      gradeLen = 2;
   else
      gradeLen = 3;

   int numOfDots = 30 - nameLen - gradeLen;
}


So now we can just start at 1 and loop up until we get to that amount. We'll create a variable to store the dots in.

code:
String getFormattedString(String name, int grade) {
   int nameLen = name.length();
   int gradeLen;

   if (grade < 10)
      gradeLen = 1;
   else if (grade < 100)
      gradeLen = 2;
   else
      gradeLen = 3;

   int numOfDots = 30 - nameLen - gradeLen;

   String dots = "";

   for (int counter = 1; counter <= numOfDots; counter++)
      dots = dots + "*";
}


Now, to compose the final result, we simple add the dots to the name, and the grade to the end of that. Then we take that string and return it from our function. We "spit" it out the other side of our "black box".

code:
String getFormattedString(String name, int grade) {
   int nameLen = name.length();
   int gradeLen;

   if (grade < 10)
      gradeLen = 1;
   else if (grade < 100)
      gradeLen = 2;
   else
      gradeLen = 3;

   int numOfDots = 30 - nameLen - gradeLen;

   String dots = "";

   for (int counter = 1; counter <= numOfDots; counter++)
      dots = dots + "*";

   String finalResult = name + dots + grade;

   return finalResult;
}


We can then use this as follows:

code:
class Exercise {
   public static String getFormattedString(String name, int grade) {
      int nameLen = name.length();
      int gradeLen;

      if (grade < 10)
         gradeLen = 1;
      else if (grade < 100)
         gradeLen = 2;
      else
         gradeLen = 3;

      int numOfDots = 30 - nameLen - gradeLen;

      String dots = "";

      for (int counter = 1; counter <= numOfDots; counter++)
         dots = dots + "*";
   }

   public static void main(String[] args) {
      String output = getFormattedString("John Doe", 87);
      System.out.println(output);
   }
}


Object-Oriented Design

Further analyzing this problem, the two pieces of data are related. Together they describe a student. This is our "thing" for this program. What we do to this thing is take the data that represents it (name and grade) and stick them together in a certain way.

So we have a thing (or "object") in the form of a student, and an action ("method") in the form of getting our formatted string. We need a way to describe a student object, and the action that it can perform on itself.

In Java (and many other languages) we call this a "class". The Student class now has attributes called name and grade. These we say are private to the class. That is, only a student can know its own name and grade. It can elect to share that information with others, but they cannot access it without permission.

code:
class Exercise {
   class Student {
      private String name;
      private int grade;
   }
}


Ok, so that's all well and good, but this doesn't do much of anything at all, and nothing useful as far as we're concerned.

We can, however, create a new student that will have a name and a grade. Of course, since we haven't provided any information as to what those are, the student object will be meaningless. To provide some initial information, we need a special method called a "constructor".

The constructor will take as input an initial name, and an initial grade, and what makes it special is that it doesn't return anything. Not even "void". Of course, the constructor is "public", so that anyone can create a new student.

Inside the constructor, we'll set the student's name and grade.

A note on Java, specifically: the constructor method always has the same name as the class.

code:
class Exercise {
   class Student {
      private String name;
      private int grade;
     
      public Student(String initialName, int initialGrade) {
         name = initialName;
         grade = initialGrade;
      }
   }
}


So now we can create a new Student in our "main" method.

code:
class Exercise {
   class Student {
      private String name;
      private int grade;
     
      public Student(String initialName, int initialGrade) {
         name = initialName;
         grade = initialGrade;
      }
   }
   
   public static void main(String[] args) {
      Student johnDoe = new Student("John Doe", 89);
   }
}


Again, we can't really do anything with this, so we have to add a public method to get our specially formatted string, as detailed in the getFormattedString method. In the case of the Student class, we'll use the method name toString. This is the method that is, by convention, used when another class is trying to figure out what an object looks like as a string. For instance, System.out.println.

code:
class Exercise {
   class Student {
      private String name;
      private int grade;
     
      public Student(String initialName, int initialGrade) {
         name = initialName;
         grade = initialGrade;
      }
     
      public String toString() {
         int nameLen = name.length();
         int gradeLen;
        
         if (grade < 10)
            gradeLen = 1;
         else if (grade < 100)
            gradeLen = 2;
         else
            gradeLen = 3;
        
         int numOfDots = 30 - nameLen - gradeLen;
        
         String dots = "";
        
         for (int counter = 1; counter <= numOfDots; counter++)
            dots = dots + "*";
        
         String finalResult = name + dots + grade;
        
         return finalResult;
      }
   }
   
   public static void main(String[] args) {
      Student johnDoe = new Student("John Doe", 89);
      System.out.println(johnDoe);
   }
}
Sponsor
Sponsor
Sponsor
sponsor
grasshopper




PostPosted: Mon Apr 05, 2004 10:29 pm   Post subject: (No subject)

ooh my gosh wtd.. you just summarized wht my student teacher has been tryin to teach us for like two weeks.. i understand it now!.. you guys are SOOO cool!
but i`m taught to put everything in the main.. that`s how my teacher has been teaching us.. that`s stupid if were going to learn to do it the right way later (in university maybe..(the way you guys are)..

Hacker Dan i`m using BlueJ to run the programs.. and its a ICS3M1 course..

the programs that i`ve been asking for assistant on are not what is needed for the course assignments but similar to help me out a little more.. and not actually get the code for the program (as i should be able to program myself) ..reasons why i find it harder is i guess because i advanced a grade in computer science..and my teacher (student teacher actually.that`s been teaching right now.. has an accent so it`s very hard to understand)..
In Newmarket near Toronto (noo idea where you`re from so incase you don`t know)... in Ontario of course)
Dan




PostPosted: Tue Apr 06, 2004 3:55 pm   Post subject: (No subject)

ah i see, i am doing the grade 12 level of compsci, alougth i fished the noraml cruimale stuff along time ago and am working on amsents from a book they uses at 1st year U of W and some of there permade methods are simmer to the BlueJ ones i gusse.

ya i can be hard to lrean compsci from a teacher that is unschure of them there self. alougth i chage schools this year so i fainly have a compsci teacher who knows what OOP even means Razz
Computer Science Canada Help with programming in C, C++, Java, PHP, Ruby, Turing, VB and more!
wtd




PostPosted: Tue Apr 06, 2004 9:36 pm   Post subject: (No subject)

Glad I could help. Does this explanation shed any light on my proposed solution for your previous question about inputting ten grades and then finding the max, min, and average?

In the event it doesn't, and because I'm sitting here bored while I wait the requisite 30 minutes before swimming after eating, an analysis that should make it make sense.

Analysis

The problem involves inputting ten grades and finding the minimum grade, the maximum grade, and the average grade. Object-oriented design focuses on the data being manipulated. In this case, that data is 10 grades. We'll assume they're integer values for now. We can represent this as an array of ints in Java. So our class will be GradeCollection (I'm rethinking my original code a bit). These should be hidden within the object and not directly visble from the outside, so we declare the array private.

code:
class Exercise {
   public class GradeCollection {
      private int [] grades;
     
   }
}


Ok, that doesn't do a thing. We need a constructor which sets up the initial state of our GradeCollection object. This constructor will need to know how many grades we want to be able to collect, since we're going to make this one flexible. Oh yeah, and we should probably make sure all of those grades are initialized to some default value we'll feed to the constructor.

code:
class Exercise {
   public class GradeCollection {
      private int [] grades;
     
      public GradeCollection(int desiredLength, int defaultGrade) {
         grades = new int[desiredLength];
         for (int i = 0; i < desiredLength; i++)
            grades[i] = defaultGrade;
      }
   }
}


Now we can create a new GradeCollection object, but it can't really do anything. We need to give it actions ("methods"). Firstly we'll probably want a way for people looking at this thing from the outside to figure out how many grades it can store. Since the array is private, though, we can't directly see it from outside of the black box that is our object.


code:
class Exercise {
   public class GradeCollection {
      private int [] grades;
     
      public GradeCollection(int desiredLength, int defaultGrade) {
         grades = new int[desiredLength];
         for (int i = 0; i < desiredLength; i++)
            grades[i] = defaultGrade;
      }

      public int length() {
         return grades.length;
      }
   }
}


Next we'll want a method which finds the minimum value in the array and shows it to us.


code:
class Exercise {
   public class GradeCollection {
      private int [] grades;
     
      public GradeCollection(int desiredLength, int defaultGrade) {
         grades = new int[desiredLength];
         for (int i = 0; i < desiredLength; i++)
            grades[i] = defaultGrade;
      }

      public int length() {
         return grades.length;
      }

      public int minGrade() {
         int min = grades[0];
         for (int i = 1; i < length(); i++)
            if (min > grades[i])
               min = grades[i];
         return min;
      }
   }
}


Now, I'll want another method, using almost exactly the same algorithm which finds the maximum grade.

code:
class Exercise {
   public class GradeCollection {
      private int [] grades;
     
      public GradeCollection(int desiredLength, int defaultGrade) {
         grades = new int[desiredLength];
         for (int i = 0; i < desiredLength; i++)
            grades[i] = defaultGrade;
      }

      public int numberOfGrades() {
         return grades.length;
      }

      public int minGrade() {
         int min = grades[0];
         for (int i = 1; i < numberOfGrades(); i++)
            if (min > grades[i])
               min = grades[i];
         return min;
      }

      public int maxGrade() {
         int max = grades[0];
         for (int i = 1; i < numberOfGrades(); i++)
            if (max < grades[i])
               max = grades[i];
         return max;
      }
   }
}


Now, I need to find the average grade. Really, this is two issues. First I need to find the sum of all of the grades. This doesn't really need to be visible from outside, though, so let's make it private. The second part is to divide that number by the number of grades in the collection. For the greatest accuracy, let's make the average a floating point number.

code:
class Exercise {
   public class GradeCollection {
      private int [] grades;
     
      public GradeCollection(int desiredLength, int defaultGrade) {
         grades = new int[desiredLength];
         for (int i = 0; i < desiredLength; i++)
            grades[i] = defaultGrade;
      }

      public int length() {
         return grades.length;
      }

      public int minGrade() {
         int min = grades[0];
         for (int i = 1; i < numberOfGrades(); i++)
            if (min > grades[i])
               min = grades[i];
         return min;
      }

      public int maxGrade() {
         int max = grades[0];
         for (int i = 1; i < numberOfGrades(); i++)
            if (max < grades[i])
               max = grades[i];
         return max;
      }

      private int sumOfGrades() {
         int sum = 0;
         for (int i = 1; i < numberOfGrades(); i++)
            sum  = sum + grades[i];
         return sum;
      }

      public double averageGrade() {
         return ((double)sumOfGrades()) / numberOfGrades();
      }
   }
}


Oh yeah, and we'll need a way to add a grade at a particular location, since our array of grades isn't accessible from outside.

code:
class Exercise {
   public class GradeCollection {
      private int [] grades;
     
      public GradeCollection(int desiredLength, int defaultGrade) {
         grades = new int[desiredLength];
         for (int i = 0; i < desiredLength; i++)
            grades[i] = defaultGrade;
      }

      public int length() {
         return grades.length;
      }

      public int minGrade() {
         int min = grades[0];
         for (int i = 1; i < numberOfGrades(); i++)
            if (min > grades[i])
               min = grades[i];
         return min;
      }

      public int maxGrade() {
         int max = grades[0];
         for (int i = 1; i < numberOfGrades(); i++)
            if (max < grades[i])
               max = grades[i];
         return max;
      }

      private int sumOfGrades() {
         int sum = 0;
         for (int i = 1; i < numberOfGrades(); i++)
            sum  = sum + grades[i];
         return sum;
      }

      public double averageGrade() {
         return ((double)sumOfGrades()) / numberOfGrades();
      }

      public void addGrade(int position, int grade) {
         grades[position] = grade;
      }
   }
}


Now we have everything necessary to create a main routine.

code:
class Exercise {
   public class GradeCollection {
      private int [] grades;
     
      public GradeCollection(int desiredLength, int defaultGrade) {
         grades = new int[desiredLength];
         for (int i = 0; i < desiredLength; i++)
            grades[i] = defaultGrade;
      }

      public int length() {
         return grades.length;
      }

      public int minGrade() {
         int min = grades[0];
         for (int i = 1; i < numberOfGrades(); i++)
            if (min > grades[i])
               min = grades[i];
         return min;
      }

      public int maxGrade() {
         int max = grades[0];
         for (int i = 1; i < numberOfGrades(); i++)
            if (max < grades[i])
               max = grades[i];
         return max;
      }

      private int sumOfGrades() {
         int sum = 0;
         for (int i = 1; i < numberOfGrades(); i++)
            sum  = sum + grades[i];
         return sum;
      }

      public double averageGrade() {
         return ((double)sumOfGrades()) / numberOfGrades();
      }
   }

   public static void main(String[] args) {
      BufferedReader keyboard = new BufferedReader(
         new InputStreamReader(System.in));

      GradeCollection grades = new GradeCollection(10, 0);

      for (int i = 0; i < grades.numberOfGrades(); i++) {
         System.out.print("Please input a grade: ");
         int inputGrade = Integer.parseInt(keyboard.readLine());
         grades.addGrade(inputGrade, i);
      }

      System.out.println("Max Grade: " + grades.maxGrade());
      System.out.println("Min Grade: " + grades.minGrade());
      System.out.println("Avg Grade: " + grades.averageGrade());
   }
}
grasshopper




PostPosted: Mon Apr 19, 2004 8:04 pm   Post subject: (No subject)

wtd wrote:
Yes. Teachers aren't always right. Wink

code:
class Exercise {
   public static void printStuff() {
     // code here
   }

   public static void main(String[] args) {
      printStuff();
   }
}


heey... thanks sooo much.. our teacher FINALLY showed us how.. well actually she didn`t she gave us an assignment and told us we had to call them.. so i used that code you gave me.. great help!.. i know this is an old reply.. not sure you`ll even get this.. but thanks SOO mcuh Smile
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 2 of 2  [ 20 Posts ]
Goto page Previous  1, 2
Jump to:   


Style:  
Search: