Classes and subclasses given as String input - question

Hello, I am new in Java so please don't laugh at my question!!
I have a method as the following and I am trying to store objects of the type Turtle in a vector. However the objects can also be of Turtle subclasses: ContinuousTurtle, WrappingTurtle and ReflectingTurtle. The exact class is determined by the String cls which is input by the user.
My question is, how can I use cls in a form that I don't have to use if-else statements for all 4 cases? (Imagine if I had 30 subclasses).
I have tried these two and similar methods so far but they return an error and Eclipse is not of much help in this case.
Simplified methods:
//pre:  cls matches exactly the name of a valid Turtle class/subclass
//post: returns vector with a new turtle of type cls added to the end
private Vector<Turtle> newturtle(Vector<Turtle> storage, String cls){
     Turtle t = new cls(...);
     storage.add(t);
     etc.
private Vector<Turtle> newturtle(Vector<Turtle> storage, String cls){
     Turtle t = new Turtle<cls>(...);
     storage.add(t);
     etc.
}Thanks for your help.
p.s.: I didn't know whether to post this question here or under Generics.

a Factory is atually very simple (100x simpler than reflection).
example:
class TurtleFactory
  public Turtle makeTurtle(String typeOfTurtle)
    if (typeOfTurtle.equals("lazy") { return new LazyTurtle(); }
    else if (typeOfTurtle.equals("fast") { return new FastTurtle(); }
    <etc>
}While at first this doesn't look any better than your original problem, what we've done is made a class that is responsible for all the types of turtles. This will also benefit in case some turtles need initialization or need something passed to their constructor. You encapsulate all that knowledge in one place so you rcode doesn't become littered with it else ladders.

Similar Messages

  • Classes and SubClasses

    How do you explicitly call a certain constructor in the superclass in the cunstructor of the subclass?
    For clarity look at the following example:
    This is ClassOne:
    import java.io.*;
    public class ClassOne {
    public ClassOne() {
    System.out.println("ClassOne Constructor One");
    public ClassOne(String strX) {
    System.out.println("ClassOne Constructor Two");
    This is ClassTwo
    import java.io.*;
    public class ClassTwo extends ClassOne {
    /** Creates a new instance of ClassTwo */
    public ClassTwo() {
    System.out.println("ClassTwo First Constructor");
    public ClassTwo(String strX) {
    System.out.println("ClassTwo Second Constructor");
    public static void main(String[] args) {
    ClassTwo X = new ClassTwo("X");
    So the problem is I want the second constructor of ClassTwo to call the second constructor in ClassOne instead of the first constructor of ClassOne.

    Hi billy,
    As passgodev suggested you have to insert a super("X") statement in your code.I will explain you why this happens:
    public ClassTwo() {
    System.out.println("ClassTwo First Constructor");
    public ClassTwo(String strX) {
    System.out.println("ClassTwo Second Constructor");
    }The compiler inserts a no-argument super() call as the first statement in your constructors to call the super class constructors.So,your code changes to:
    public ClassTwo() {
    super();
    System.out.println("ClassTwo First Constructor");
    public ClassTwo(String strX) {
    super();
    System.out.println("ClassTwo Second Constructor");
    }So,you just need to pass arguments to the super() method to call the overloaded constructor of ClassOne i.e
    public ClassTwo(String strX) {
    super(strX);
    System.out.println("ClassTwo Second Constructor");
    }I hope that helps!!!

  • Classes and Subclasses or alternative.

    Hi all,
    I have the following 'issue': I want to create / update / retrieve BP relationships. My idea is to create a superclass with all general data for a relationship like Partner 1 & 2, type of relationship (employer-employee, husband-wife etc.). So far so good, but now it comes. All relationships have different attributes (created in CRM with Easy Enhancement Workbench, comparable to customer includes).
    Does it make sense to create a subclass per relationship type, because based on that different logic has to be processed. Or put all these attributes, whether they belong to relationship type A, or B, in the same superclass?
    Normally I would say the second option is better / more logical and put them all in ONE (super)class, but since every relationship is a specialization of the superclass due to all the different attributes, it would also make sense to create a new subclass for every relationship type. I actually want to avoid, using IF statement within the class (IF relationship A, ELSEIF relationship B, etc.), because when creating a new relationship type, I would have to change the superclass over and over again.
    Thanks,
    Micky.

    Hi Matt,
    thanks againg for the reply. Just to make sure you understand it, this is the case.
    I want to create a superclass with all standard attributes for a BP relationship like start- and end date, Business partner 1 and Business partner 2 (BP that have a relationship).
    Next I want to create a subclass / or interface (or even both?), but I'm not quite sure which one would be the better option.
    So what I can do is create a new subclass per relationship type (like Is parent of, is married to, is working at etc.). Depending on the subclass the processing is done, so every subclass will have general methods inherited from the superclass, and specific methods per relationship. Or would it be better to create ONE subclass for all relationships and use an interface in which the specific methods are defined?
    When I look at it, then I can use the 'analogy': Subclass B (relationship X) is a Relationship (Superclass). This is true for every subclass which indeed is a relationship of a certain type. Hope this makes sense.
    Kind regards,
    Micky.

  • HELP, date class and parsing input

    I have reviewed many posts in these forums and have found that detail gets the best results so I apologize in advance if this is detailed. I am taking a Java class and am not doing so hot. The last time I programmed was in 1998 and that was Ada, I very soon moved to Networking. I guess those that can't program become networkers, I don't know, but I am frustrated here.
    Any how I am trying to write a rather simple program, but it is the manipulation of the date I am having difficulty with. Here are the requirements:
    Overall Requirements
    Create a class named Date that stores date values and prints out the date in either a pure numeric format or a name and number format (see sample session for format details).
    Date.java class file
    ? Date objects should store the date in two int instance variables &#9472; day and month, and it should include the String instance variable, error, initialized with null.
    Implement a 1-parameter Date constructor that receives a dateStr string parameter and performs complete error checking on the given dateStr value. The Date constructor is the entity that?s responsible for date error checking. That way, if a Date object is instantiated and if there are no errors, then you?re guaranteed that the Date object holds a legitimate date value. If any kind of error occurs, change the value of the error instance variable to a non-null string value, using an appropriate concatenation of a string constant, input substring, and/or API exception message.
    Constructors use the same exception handling rules as methods: In a try block, include the parsing of the month and day substrings and other error-checking logic that will not work if parsing fails.
    ? Take into account the actual number of days in each month, but assume that there are always 28 days in February.
    ? To extract day and month numbers from the given date string, use String?s indexOf method to find the location of the slash character, and String?s substring method to extract month and day substrings from the input string.
    ? Include a method for printing the date with a numeric format. Use the zero-pad flag in a printf method call to get exactly two digits for each month and day.
    ? Include a method for printing the date with an alphabetic format.
    Include a getError method which returns the value of the error instance variable.
    DateDriver.java class file : In your driver class, include a loop that repeatedly:
    ? Asks the user to enter a date or ?q? to quit. ? If the entry is not ?q?, instantiate a Date object.
    ? If the error variable is null: o Print the date using numeric format.o Print the date using alphabetic format. Otherwise, print the value of the error variable.
    I want to figure this out on my own as much as possible but have until tomorrow night to do so..............I need to understand how I can use Strings indexOf to parse the dateStr so I can locate the /. I see I can use it to find the position of a specified character, but I am not sure of the syntax I need to use. But then once I find the / I need to use the String's substring method to extract month and day. I think I might be able to get that, if I can get the / figured out.
    The below is what I have in my Class and my Driver so far:
    *DateDriver.java (driver program)
    * Christine Miller-Lane
    *Overall Requirements
    *Create a class named Date that stores date values and prints out the date in either a pure numeric
    format or a name and number
    *format (see sample session for format details).
    *DateDriver.java class file
    *In your driver class,
    *????????? If the error variable is null:
    *     &#9702;     Otherwise, print the value of the error variable.
    import java.util.*;
    public class DateDriver
    Date datevalue;
    public static void main(String[] args)
         Scanner stdIn = new Scanner(System.in);
         while (!xStr.equalsIgnoreCase("q"))
         try
              System.out.println("Enter a date in the form mm/dd ("q" to quit): ";
              value = stdIn.nextLine();
              datevalue = new Date(value);                                                        //instaniate the date object
              System.out.println //print date in numeric format
              System.out.println //print date in alphabetic format
              break;
              catch
              System.out.println("print value of error variable.");
              stdIn.next(); // Invalid input is still in the buffer so flush it.
         } //endloop
         }//end main
    } //end class?
    * Date.java
    * Christine Miller-Lane
    *Overall Requirements
    *Create a class named Date that stores date values and prints out the date in either a pure numeric format or a name
    *and number format (see sample session for format details).
    *Date.java class file
    *????????? Date objects should store the date in two int instance variables &#9472; day and month, and it should include
    *the String instance variable, error, initialized with null.
    *     ?     Implement a 1-parameter Date constructor that receives a dateStr string parameter and performs complete
    *     error checking on the given dateStr value. The Date constructor is the entity that?s responsible for date error
    *     checking. That way, if a Date object is instantiated and if there are no errors, then you?re guaranteed that the
    *     Date object holds a legitimate date value. If any kind of error occurs, change the value of the error instance
    *     variable to a non-null string value, using an appropriate concatenation of a string constant, input substring,
    *     and/or API exception message.?
    *     ?     Constructors use the same exception handling rules as methods: In a try block, include the parsing of the
    *     month and day substrings and other error-checking logic that will not work if parsing fails.
    *????????? Take into account the actual number of days in each month, but assume that there are always 28 days in February.
    *????????? To extract day and month numbers from the given date string, use String?s indexOf method to find the
    *location of the slash character, and String?s substring method to extract month and day substrings from the input string.
    import java.util.*;
    public class Date
         Scanner stdIn = new Scanner(System.in);
         boolean valid = false
         int day;
         int month;
         String error = null;
         String dayStr;
         String monthStr;
         String dateStr;
         public Date(String dateStr)
    // Look for the slash and set appropriate error if one isn't found. use String?s indexOf method to find the
    //location of the slash character and String?s substring method to extract month and day substrings from the input string.
    // Convert month portion to integer. Catch exceptions and set appropriate error if there are any.
    Integer.parseInt(dateStr);
    // Validate month is in range and set appropriate error if it isn't.
    // Convert day portion to integer. Catch exceptions and set appropriate error if there are any.
    // Validate day is in range based on the month (different days per month) and set appropriate error if it isn't.
    //public void printDate()      //Include a method for printing the date with a numeric format. Use the zero-pad flag in a printf method
                                       //call to get exactly two digits for each month and day.
    //{                                   //Include a method for printing the date with an alphabetic format.      
    //     } // end print report
    //     public getError()
                                  //Include a getError method which returns the value of the error instance variable.
    }//end class Date
    Here is sample out put needed::::::::
    Sample Session:
    Enter a date in the form mm/dd ("q" to quit): 5/2
    05/02
    May 2
    Enter a date in the form mm/dd ("q" to quit): 05/02
    05/02
    May 2
    Enter a date in the form mm/dd ("q" to quit): 52
    Invalid date format ? 52
    Enter a date in the form mm/dd ("q" to quit): 5.0/2
    Invalid format - For input string: "5.0"
    Enter a date in the form mm/dd ("q" to quit): 13/2
    Invalid month ? 13
    Enter a date in the form mm/dd ("q" to quit): 2/x
    Invalid format - For input string: "x"
    Enter a date in the form mm/dd ("q" to quit): 2/30
    Invalid day ? 30
    Enter a date in the form mm/dd ("q" to quit): 2/28
    02/28
    February 28
    Enter a date in the form mm/dd ("q" to quit): q
    I am trying to attack this ONE STEP at a time, even though I only have until Sunday at midnight. I will leave this post and get some rest, then attack it again in the morning.
    Edited by: stillTrying on Jul 12, 2008 8:33 PM

    Christine,
    You'r doing well so far... I like your "top down" approach. Rough out the classes, define ALL the methods, especially the public one... but just sketch out the requirements and/or implementation with a few comments. You'll do well.
    (IMHO) The specified design is pretty crappy, especially the Exception handling
    [The Constructor] performs complete error checking on the given dateStr value. The Date constructor is the entity that?s responsible for date error checking. That way, if a Date object is instantiated and if there are no errors, then you?re guaranteed that the Date object holds a legitimate date value. If any kind of error occurs, change the value of the error instance variable to a non-null string value, using an appropriate concatenation of a string constant, input substring, and/or API exception message.Please allow me to shred this hubris piece by piece.
    [The Constructor] performs complete error checking on the given dateStr value. The Date constructor is the entity that?s responsible for date error checking.Umm... Well I suppose it could... but NO, the constructor should delegate such "complex validation" to a dedicated validate (or maybe isValid) method... which might even be made publicly available... it's a good design.
    That way, if a Date object is instantiated and if there are no errors, then you?re guaranteed that the Date object holds a legitimate date value. If any kind of error occurs, change the value of the error instance variable to a non-null string value ...Utter Bollocks! When passed an invalid input string the, Date constructor should throw an InvalidDataException (or similar). It should not SILENTLY set some dodgy error errorMessage attribute, which is returned later by a "print" method. We tried that in masm, fortran, ada, basic, c, and pascal for twenty odd years. It sucked eggs. And it STILL sucks eggs. Java has a "proper" try/catch exception handling mechanism. Use it.
    I mean, think it through...
      someDate = get a date from the user // user enters invalid date, so someDate is null and errMsg is set.
      report = generateReport() // takes (for the sake of argument) three hours.
      emailReport(someDate, report) // only to fail at the last hurdle with an InvalidDataException!And anyways... such implementation details are traditionally the implementors choice... ie: it's usually between the programmer and there tech-manager (if they're lucky enough to have one).
    Cheers. Keith.

  • Search given string array and replace with another string array using Regex

    Hi All,
    I want to search the given string array and replace with another string array using regex in java
    for example,
    String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
    String fromValue[] = {"you", "search", "for", "any"}
    String toValue[] = {"me", "dont search", "never", "trip"}
    so the string "you" needs to be converted to "me" i.e you --> me. Similarly
    you --> me
    search --> don't search
    for --> never
    any --> trip
    I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
    I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
    One Single regular expression which matches the pattern and solve the issue.
    the output should be as:
    If me wish to don't search never trip etc...,
    Please help me to resolve this.
    Thanks In Advance,
    Kathir

    As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
    import java.util.regex.*;
    public class Test
      static final List<String> oldWords =
          Arrays.asList("you", "search", "for", "any");
      static final List<String> newWords =
          Arrays.asList("me", "dont search", "never", "trip");
      public static void main(String[] args) throws Exception
        String str = "If you wish to search for any of these characters, "
            + "they must be preceded by the character to be interpreted";
        System.out.println(doReplace(str));
      public static String doReplace(String str)
        Pattern p = Pattern.compile("\\b\\w+\\b");
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find())
          int pos = oldWords.indexOf(m.group());
          if (pos > -1)
            m.appendReplacement(sb, "");
            sb.append(newWords.get(pos));
        m.appendTail(sb);
        return sb.toString();
    } This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

  • FM/Class to find the class and characterstics for a given material

    Hi All,
    Is there any Class/FM to find the class and characterstics for a given material.I tried some BAPI_OBJCL* BAPI's but lot of the BAPI's need classnum as input parameter. But i need a BAPI or tables or class which can give the class and its characterstic values for a given material.

    Hi Ben
             Try ..
    BAPI_OBJCL_GETCLASSES
    BAPI_OBJCL_CREATE

  • A question about class and interface? please help me!

    the following is program:
    interface A{
    public class B implements A{
    public static void main(String [] args){
    A a = new B();
    System.out.println(a.toString());
    }i want to ask a question, the method toString() is not belong to interface A, why a can call method toString()? the interface call the method that isn't belong to, why? please help me...

    because a.toString() call the method toString() of class Object because B implements A, but extends Object and in the class Object there is a method toString(). infact if you override the method toString() in class B, a.toString() call toString() in class B.
    try this:
    interface A {}
    public class B implements A
      public String toString()
        return "B";
      public static void main(String [] args)
        A a = new B();
        System.out.println(a.toString());
      }by gino

  • Document Classes and other Questions

    Basically, i am working on an application that will eventually be deployed to the desktop as an AIR application.
    I am wanting to create an Analogue clock and Digital clock with a button that toggles the display between either one when pressed. As well as this, i will be wanting to display the Date below, i am having a number of issues however.
    I have the code sorted for three of the four components, i have not attempted to figure out the button thus far as i would be more than happy to have the digital clock, analogue clock and date all being displayed on a drag and drop desktop application first. When i say i have it sorted, i have a fully working analogue clock which i have managed to display on the desktop through air on its lonesome, however, i did not include the drag and drop function. For the digital clock and date components i am not sure how to configure them into document classes. The main issue i am having is i do not know if you can reference a dynamic text box within a movie clip to a document class.
    This is the code to show the date
    [code]{
    var currentTime:Date = new Date();
    var month:Array = new Array("January","February","March","April","May","June","July","August","September","Octo ber","November","December");
    var dayOfWeek:Array = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
    date_text.text = dayOfWeek[currentTime.getDay()] + " " + currentTime.getDate() + " " + month[currentTime.getMonth()] + " " + currentTime.getFullYear();
    [/code]
    I have put the actionscript frame inside the movie clip file, and i have given both the movie clip, and the dynamic text box within the movie clip the instance name "date_text".
    Basically, i am just struggling in how to put this code into a working document class, since the digital clock and date functions are both, some what similar, i feel the solution to one will more than likely lead to me discovering the solution for the other.
    The other problem i am having, i do not know how i will display all of the components on one air application. I am assuming, that you create one other document class file which links the other four together? i have tried to do this by just linking a new FLA file with the analogue clock, but it does not work. The code for that is below.
    [code]package
              import flash.events.Event;
              import flash.display.MovieClip;
              public class time1 extends MovieClip
                        public var now:Date;
                        public function time1()
                                  // Update screen every frame
                                  addEventListener(Event.ENTER_FRAME,enterFrameHandler);
                        // Event Handling:
                        function enterFrameHandler(event:Event):void
                                  now = new Date();
                                  // Rotate clock hands
                                  hourHand_mc.rotation = now.getHours()*30+(now.getMinutes()/2);
                                  minuteHand_mc.rotation = now.getMinutes()*6+(now.getSeconds()/10);
                                  secondHand_mc.rotation = now.getSeconds()*6;
    [/code]
    That is the original clock document class (3 Movie clips for the moving hands, and the clock face is a graphic, which i may have to reference somehow below)?
    [code]package
              import flash.display.MovieClip;
              public class main extends MovieClip
                        public var hourHand_mc:time1;
                        public var minuteHand_mc:time1;
                        public var secondHand_mc:time1;
                        public function main()
                                  hourHand_mc = new SecondHand();
                                  addChild(mySecondHand);
                                  hourHand_mc.x = 75;
                                  hourHand_mc.y = 75;
                                  minuteHand_mc = new SecondHand();
                                  addChild(mySecondHand);
                                  minuteHand_mc.x = 75;
                                  minuteHand_mc.y = 75;
                                  secondHand_mc = new SecondHand();
                                  addChild(mySecondHand);
                                  secondHand.x = 75;
                                  secondHand.y = 75;
    }[/code]
    This is my attempt at creating the main document class in a seperate FLA file to attempt to load the analogue clock, and later on the Digital Clock, Date Function and Toggle Display button in the same AIR application.
    Any help on this is much appreciated, i have been reading up a lot on it through tutorials and the like, but i can't seem to fully grasp it.

    why do you have code in a movieclip?
    if you want to follow best practice and use a document class you should remove almost all code from timelines.  the only timeline code that might be reasonably used would be a stop() on the first frame of multiframe movieclips.
    so, you should have a document class.  that could contain all your code but it would be better to just have your document class create your 2 clocks and date objects and possibly manage toggling between the two clocks.  you could have a separate class the tracks the time and date and that class is used by your two clock classes and your date class.

  • Getting a character at a given index in a String and returing as a String

    Hello,
    How do I simply grab one character in a string and return it as a string? I saw the substring() method but it does not like when I invoke:
    String test = "abcd";
    test = test.substring(0,0);
    **Above produces a runetime error. ***I need something that does this:
    String test = "abcd"
    test.needtodo(0) returns String "a".
    test.needtodo(1) returns String "b".
    ETC.
    ---- Thanks for the help.

    Ok I used Kaj's method, but what I am trying to do still inst working properly. Here is what I am trying to do:
    public String stringToBinaryStringWithLeadingZeroz(String input) {
         String binaryString="";
         int sizeOf = input.length();
         for(int i=0; i < sizeOf; i++)
              int intRepresentation = Integer.parseInt(String.valueOf(input.charAt(i)), 16);
              binaryString += Integer.toBinaryString(intRepresentation);
         return binaryString;
    }I am trying to take in a String that is Hex and return a string that is binary with leading zeros.
    So if the input is: stringToBinaryStringWithLeadingZeroz("3");
    It should be returning 0011 but its still only returning 11. It shouldnt be returning 0011 though. I am passing each character indivudally into the method toBinaryString() which just returns the result and appends onto the result.
    ** SCRATCHING MY HEAD **

  • Can formula node take string input and output string?

    I am wondering if the formula node can take string input variable and output string variable after calculation. otherwise I have to output integers and then use case structure to select different output strings, that is kind of redundant in coding.
    ping

    If you are just trying to read lines that have mixed formatting, you don't need any script nodes.
    Can you attach a tpyical flne and a description of the desired read operation so we have a better idea what you are trying to do? Do all lines have the same overall format?
    LabVIEW Champion . Do more with less code and in less time .

  • Question about Classes, Abstract  Classes and Interfaces.

    I have been experimenting with Classes, Abstract Classes and Interfaces and wonder if anyone can explain this to me.
    I was looking for a way to assign a value to a variable and then keep it fixed for the session and have devised this.
    First I create an abstract class like this:
    public abstract class DatabaseConnection {
    private static String ServerName = null;
    public static void setServerName(String serverName) {
              ServerName = serverName;
         public static String getServerName() {
              return ServerName;
    }and then I created an interface
    public interface DatabaseAccess {
         String servername = DatabaseConnection.getServerName();
    }And finally the class itself with some test lines in it so I could see what was going on:
    public class CreateDatabase extends DatabaseConnection implements DatabaseAccess {
         public static void main (String args[]){
              new CreateDatabase();
         public CreateDatabase(){     
              setServerName("Server Name 1");
              System.out.println ("Before update ");
              System.out.println ("ServerName from Interface           = " + servername);
              System.out.println ("ServerName from Abstract Class = " + getServerName());
              System.out.println ("After update ");
              setServerName("Server Name 2");
              System.out.println ("ServerName from Interface           = " + servername);
              System.out.println ("ServerName from Abstract Class = " + getServerName());
              System.out.println ("==========================");
    }The output I get from the above is:
    Before update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 1
    After update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 2
    ==========================I also tried this in another class which calls the above class to see if I get the same effect
    public class CheckDatabaseAccess {
         public static void main (String args[]){
              new CreateDatabase();
              CreateDatabase.setServerName("Server 3");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
              CreateDatabase.setServerName("Server 4");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
              CreateDatabase.setServerName("Server 5");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
    }The output of which is this:
    Before update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 1
    After update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 2
    ==========================
    CreateDatabase Server Name 1
    CreateDatabase Server Name 1
    CreateDatabase Server Name 1Can anyone explain why I appear to only be able to change or set the ServerName only the once?
    Is this the correct way to do it? If it is it's exactly what I am looking for, a way to set the value of variable once in a session and then prevent it being changed.
    Or is there a better way of doing this.
    What I want to use this for is for example, storing the accesses to a database on a server. I won't know what server the database will be stored on nor what the database is called so I create an INI file which stores this information in encrypted format, which is set by the database administrator. It occurs to me I can use this method to then retrieve that data once and once only from the INI file and use that throughout the life of the session to access the database.
    Any help appreciated
    Regards
    John

    Not gonna read all of it, but this jumps out:
    public abstract class DatabaseConnection {
    private static String ServerName = null;
    public interface DatabaseAccess {
         String servername = DatabaseConnection.getServerName();
    }You have two completely separate variables (with two different names, for that matter, since you were inconsistent in your capitalization, but it wouldn't make a difference if they did have the same name with the same case). And the one in the interface is implicitly public, static, and final.
    Anytime you refer to "servername" through a reference of type DatabaseAccess, it refers to the one declared in the interface.
    Anytime you refer to "ServerName" inside the DatabaseConnection class, it refers to the one declared in that class.

  • I recently upgraded my Macbook Air to Mountain Lion and now I cannot seem to find my "notes", regardless of the countless answers given to people with questions similar to me.   Surely Apple wouldn't make you lose all your important information.   If some

    I recently upgraded my Macbook Air to the mighty "Mountain Lion" and now I cannot seem to find my "notes", regardless of the countless answers given to people with questions similar to me.
    Surely Apple wouldn’t make you lose all your important information-or they would be "bad apples".
    If someone has a solution, please please please help me find my lovely notes! (Step by step would be most helpful). Cyber high fives and Smiles will be rewarded graciously.

    I recently upgraded my Macbook Air to the mighty "Mountain Lion" and now I cannot seem to find my "notes", regardless of the countless answers given to people with questions similar to me.
    Surely Apple wouldn’t make you lose all your important information-or they would be "bad apples".
    If someone has a solution, please please please help me find my lovely notes! (Step by step would be most helpful). Cyber high fives and Smiles will be rewarded graciously.

  • Question about abstract classes and instances

    I have just read about abstract classes and have learned that they cannot be instantiated.
    I am doing some exercises and have done a class named "Person" and an abstract class named "Animal".
    I want to create a method in "Person" that makes it possible to set more animals to Person objects.
    So I wrote this method in class Person and compiled it and did not get any errors, but will this work later when I run the main-method?
    public void addAnimal(Animal newAnimal)
         animal.add(newAnimal);
    }Is newAnimal not an instance?

    Roxxor wrote:
    Ok, but why is it necessary with constructors in abstract classes if we don�t use them (because what I have understand, constructors are used to create objects)?Constructors don't create objects. The new operator creates objects. An object's c'tor is invoked after the object has already been created. The c'tors job is to initialize the newly-created object to a valid state. Whenever a child object is created, the parent's c'tor is run before the child's c'tor, so that by the time we're inside the child's c'tor, setting up the child's state, we know that the parent (or rather the "parent part" of the object we're initializing) is in a valid state.
    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • I'm in a java programming class and i'm stuck.. so please help me guys...

    Please help me, i really need help.
    Thanks a lot guys...
    this is my error:
    C:\Temp>java Lab2
    Welcome!
    This program computes the average, the
    exams
    The lowest acceptable score is 0 and th
    Please enter the minimum allowable scor
    Please enter the maximum allowable scor
    Was Exam1taken?
    Please Enter Y N or Q
    y
    Enter the Score for Exam1:
    65
    Was Exam2taken?
    Please Enter Y N or Q
    y
    Enter the Score for Exam2:
    32
    Was Exam3taken?
    Please Enter Y N or Q
    y
    Enter the Score for Exam3:
    65
    Was Exam4taken?
    Please Enter Y N or Q
    y
    Enter the Score for Exam4:
    32
    Was Exam5taken?
    Please Enter Y N or Q
    y
    Enter the Score for Exam5:
    32
    Score for Exam1 is:65
    Score for Exam2 is:32
    Score for Exam3 is:32
    Score for Exam4 is:32
    Score for Exam5 is:32
    the Minimum is:0
    the Maximum is:0
    Can't compute the Average
    Can't compute the Variance
    Can't compute the Standard Deviation
    this is my code:
    // Lab2.java
    // ICS 21 Fall 2002
    // Read in scores for a student's exams, compute statistics on them, and print out
    // the scores and statistics.
    public class Lab2
         // Create a manager for this task and put it to work
         public static void main(String[] args)
              ExamsManager taskManager = new ExamsManager();
              taskManager.createResults();
    // ExamsManager.java for Lab 2
    // ICS 21 Fall 2002
    // make these classes in the Java library available to this program.
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    import java.text.NumberFormat;
    // ExamsManager creates managers and contains the tools (methods) they need to do their
    // job: obtaining exam information, computing statistics and printing out that information
    class ExamsManager
         // INVALID_INT: special integer value to indicate that a non-integer
         // was entered when an integer was requested. It's chosen so as not to
         // conflict with other flags and valid integer values
         public static final int INVALID_INT = -9999;
         // valid user response constants:
         public static final String YES = "Y";               // user responded "yes"
         public static final String NO = "N";               // user responded "no"
         public static final String EXIT_PROGRAM = "Q";     // user responded "leave the program NOW"
         // INVALID_RESPONSE: special String value to indicate that something other than
         // "Y", "N" or "X" was entered when said was required
         public static final String INVALID_RESPONSE = "!";
         // ABSOLUTE_MIN_SCORE and ABSOLUTE_MAX_SCORE represent the smallest
         // minimum score and the largest maximum score allowed by the
         // program. (The allowable minimum and maximum for one
         // execution of the program may be different than these, but
         // they must both lie within this range.)
         public static final int ABSOLUTE_MIN_SCORE = 0;
         public static final int ABSOLUTE_MAX_SCORE = 1000;
         // The manager needs a place to store this student's exams
         private OneStudentsWork thisWork;
         // ...places to store the min and max scores allowed for these exams
         private int minAllowedScore;
         private int maxAllowedScore;
         // ...and a place to hold input coming from the keyboard
         BufferedReader console;
         //                    -------------------- Constructor --------------------
         // ExamsManager() make managers that delegate the major tasks of the program
         public ExamsManager()
         //                    -------------------- Processing methods --------------------
         // createResults() is the "manager at work": it calls assistants to welcome the user,
         // initializes things so we can read info from the keyboard,
         // obtain the minimum and maximum allowed scores,
         // obtain a student's work and comute the statistics on it and
         // print out the scores and the statistics
         public void createResults()
              // *** YOUR CODE GOES HERE ***
              printWelcomeMessage();
              readyKeyboard();
              obtainMinAndMaxAllowedScores();
              obtainOneStudentsWork();
              printResults();
         //                    -------------------- User input methods --------------------
         // readyKeyboard() sets up an input stream object 'console' connected to the keyboard
         // so that what's typed can be read into the program and processed.
         // Do not modify this code!
         private void readyKeyboard()
                   console = new BufferedReader(new InputStreamReader(System.in));
         // obtainMinAndMaxAllowedScores() asks the user to enter the minimum
         // and maximum allowable scores for this execution of the program.
         // Both the minimum and maximum allowable scores must be between
         // ABSOLUTE_MIN_SCORE and ABSOLUTE_MAX_SCORE (inclusive). This
         // method should continue to ask the user for a minimum until a
         // valid one is entered (or EXIT_PROGRAM is entered), then continue
         // to ask the user for a maximum until a valid one is entered. If
         // the minimum entered is greater than the maximum entered, the
         // whole thing should be done again.
         public void obtainMinAndMaxAllowedScores()
              // *** YOUR CODE GOES HERE ***
              int response = INVALID_INT;
              if (response >= minAllowedScore && response <= maxAllowedScore)
                   System.out.print("Please enter the minimum allowable score:");
                   response = getIntOrExit();
              while (response > maxAllowedScore || response < minAllowedScore)
                   System.out.print("Please enter the minimum allowable score:");
                   response = getIntOrExit();
              if (response <= ABSOLUTE_MAX_SCORE && response >= ABSOLUTE_MIN_SCORE)
                   System.out.print("Please enter the maximum allowable score:");
                   response = getIntOrExit();
              while (response > ABSOLUTE_MAX_SCORE || response < ABSOLUTE_MIN_SCORE)
                   System.out.print("Please enter the maximum allowable score:");
                   response = getIntOrExit();
              /*int response;
              String allowedMin;
              boolean done = true;
              do
                   done = true;
                   System.out.print("Please enter the minimum allowable score:");
                   response = getIntOrExit();
                   allowedMin = getYNOrExit();
                   if(allowedMin == EXIT_PROGRAM)
                        System.exit(0);
                   else if (response >= ABSOLUTE_MIN_SCORE)
                        done = true;
                   else if (response >= ABSOLUTE_MAX_SCORE)
                        done = false;
                        System.out.println("INVALID: " + INVALID_INT);
                        System.out.print("Please enter the minimum allowable score:");
                        response = getIntOrExit();
              }while (!done);
    /*          System.out.print("Please enter the maximum allowable score:");
              response = getIntOrExit();
              if (response <= ABSOLUTE_MAX_SCORE)
              return response;
              else if (response <= ABSOLUTE_MIN_SCORE)
                   response = INVALID_INT;
              while (response == INVALID_INT)
                   System.out.print("Please enter the maximum allowable score:");
                   response = getIntOrExit();
              do
                   done = true;
                   System.out.print("Please enter the minimum allowable score:");
                   response = getIntOrExit();
                   String allowedMax;
                   if(allowedMin == EXIT_PROGRAM)
                        System.exit(0);
                   if (response <= ABSOLUTE_MAX_SCORE)
                        done = true;
                   else if (response <= ABSOLUTE_MIN_SCORE)
                        done = false;
                        System.out.println("INVALID: " + INVALID_INT);
                        System.out.print("Please enter the maximum allowable score:");
                        response = getIntOrExit();
              }while (!done);
         // The overall strategy to building up a student work object is
         // to have the student-bulding method call on the exam-building
         // method, which calls upon user input methods to get exam info.
         // Thus, user entered info is successively grouped together
         // into bigger units to build the entire student information set.
         // obtainOneStudentsWork() builds the five exams
         // and constructs the student work object from them
         private void obtainOneStudentsWork()
              // *** YOUR CODE GOES HERE ***
              int index = 1;
              Exam exam1 = buildOneExam(index);
              index = 2;
              Exam exam2 = buildOneExam(index);
              index = 3;
              Exam exam3 = buildOneExam(index);
              index = 4;
              Exam exam4 = buildOneExam(index);
              index = 5;
              Exam exam5 = buildOneExam(index);
              thisWork = new OneStudentsWork(exam1, exam2, exam3, exam4, exam5);
         // buildOneExam(thisTest) reads the exam information for one exam and returns an
         // Exam object constructed from this information. Uses obtainWasExamTaken() to
         // determine if the exam was taken and obtainOneScore() to get the exam score, if needed.
         private Exam buildOneExam(int thisTest)
              // *** YOUR CODE GOES HERE ***
              int score = 0;
              if(obtainWasExamTaken(thisTest))
                   score = obtainOneScore(thisTest);
              return new Exam(score);
              else
              return new Exam();
              System.out.println("Enter score for exam1:");
              Exam exam1 = new Exam(getIntOrExit());
              System.out.println("Enter score for exam2:");
              Exam exam2 = new Exam(getIntOrExit());
              System.out.println("Enter score for exam3:");
              Exam exam3 = new Exam(getIntOrExit());
              System.out.println("Enter score for exam4:");
              Exam exam4 = new Exam(getIntOrExit());
              System.out.println("Enter score for exam5:");
              Exam exam5 = new Exam(getIntOrExit());
         // obtainWasExamTaken(thisTest) keeps asking the user whether 'thisTest' was taken
         // (e.g., "Was exam 1 taken? Enter Y, N or Q", if thisTest equals 1)
         // until s/he provides a valid response. If Q is entered, we leave the
         // program immediately; if Y or N (yes or no), return true if yes, false if no
         private boolean obtainWasExamTaken(int thisTest)
              // *** YOUR CODE GOES HERE ***
              String response = INVALID_RESPONSE;
              System.out.println("Was Exam" + thisTest + "taken?");
              while (response.equals(INVALID_RESPONSE))
                   System.out.println("Please Enter" + " " + YES + " " + NO + " " + "or" + " " + EXIT_PROGRAM);
                   response = getYNOrExit();
              if (response.equals(YES))
              return true;
              else
              return false;
         // obtainOneScore(thisTest) keeps asking the user to enter a score for
         // 'thisTest' (e.g., "Enter the score for exam 1", is thisTest equals 1)
         // until s/he provides one within range or s/he tells us to exit the program.
         private int obtainOneScore(int thisTest)
              // *** YOUR CODE GOES HERE ***
              int response = INVALID_INT;
              if (response >= minAllowedScore && response <= maxAllowedScore);
                   System.out.println("Enter the Score for Exam" + thisTest + ":");
                   response = getIntOrExit();
              while (response > ABSOLUTE_MAX_SCORE || response < ABSOLUTE_MIN_SCORE)
                   System.out.println("INVALID: " + INVALID_INT);
                   System.out.println("Please Enter again:");
                   response = getIntOrExit();
              return response;
         // scoreIsWithinRange() returns true if the given score is inside of
         // the allowable range and false if it is out of range
         private boolean scoreIsWithinRange(int score)
              // *** YOUR CODE GOES HERE ***
              if (score >= minAllowedScore && score <= maxAllowedScore)
                   return true;
              else
                   return false;
         // getYNQ() reads a String from the console and returns it
         // if it is "Y" or "N" or exits the program if "Q" is entered;
         // the method returns INVALID_RESPONSE if the response is other
         // than"Y", "N" or "Q".
         // Do not modify this code!
         private String getYNOrExit()
              String usersInput = INVALID_RESPONSE;
              try
                   usersInput = console.readLine();
              catch (IOException e)
                   // never happens with the keyboard...
              usersInput = usersInput.toUpperCase();
              if (usersInput.equals(EXIT_PROGRAM))
                   System.out.println("Leaving...");
                   System.exit(0);
              if (usersInput.equals(YES) || usersInput.equals(NO))
                   return usersInput;
              else
                   return INVALID_RESPONSE;
         // getIntOrExit() reads an integer from the console and returns it.
         // If the user types in "Q", the program exits. If an integer is entered,
         // it is returned. If something that is not an integer (e.g. "Alex"), the
         // program returns INVALID_INT
         // Do not modify this code!
         private int getIntOrExit()
              String usersInput = "";
              int theInteger = 0;
              try
                   usersInput = console.readLine();
              catch (IOException e)
                   // never happens with the keyboard...
              // if the user wants to quit, bail out now!
              if(usersInput.toUpperCase().equals(EXIT_PROGRAM))
                   System.out.println("Program halting at your request.");
                   System.exit(0);
              // see if we have an integer
              try
                   theInteger = Integer.parseInt(usersInput);
              catch (NumberFormatException e)
                   // user's input was not an integer
                   return INVALID_INT;
              return theInteger;
         //                    -------------------- User output methods --------------------
         // printWelcomeMessage() prints a welcome message to the user explaining
         // what the program does and what it expects the user to do. In
         // particular, it needs to tell the user the absolute lowest and
         // highest acceptable exam scores
         private void printWelcomeMessage()
              // *** YOUR CODE GOES HERE ***
              System.out.println("Welcome!");
              System.out.println("This program computes the average, the variance, and the standard deviation of 5 exams");
              System.out.println("The lowest acceptable score is 0 and the highest is 1000");
         // printResults() prints all of the scores present, then prints the
         // statistics about them. The statistics that can have factional parts
         // -- average, variance and standard deviation -- should be printed with
         // exactly three digits after the decimal point. If a statistic could not be
         // computed, a message to that effect should print (NOT the "phony" value stored
         // in the statistic to tell the program that the statistic could not be computed).
         public void printResults()
              // These statements create a NumberFormat object, which is part
              // of the Java library. NumberFormat objects know how to take
              // doubles and turn them into Strings, formatted in a particular
              // way. First, you tell the NumberFormat object (nf) how you'd like
              // the doubles to be formatted (in this case, with exactly 3
              // digits after the decimal point). When printing a double you call
              // format to format it -- e.g. nf.format(the-number-to-format)
              NumberFormat nf = NumberFormat.getInstance();
              nf.setMinimumFractionDigits(3);
              nf.setMaximumFractionDigits(3);
              // *** YOUR CODE GOES HERE ***
              System.out.println("Score for Exam1 is:" + thisWork.getExam1().getScore());
              System.out.println("Score for Exam2 is:" + thisWork.getExam2().getScore());
              System.out.println("Score for Exam3 is:" + thisWork.getExam3().getScore());
              System.out.println("Score for Exam4 is:" + thisWork.getExam4().getScore());
              System.out.println("Score for Exam5 is:" + thisWork.getExam5().getScore());
              if (thisWork.getStatistics().getMinimum() == Statistics.CANT_COMPUTE_STATISTIC)
                   System.out.println("Can't compute the Minimum");
              else
                   System.out.println("the Minimum is:" + thisWork.getStatistics().getMinimum());
              if (thisWork.getStatistics().getMaximum() == Statistics.CANT_COMPUTE_STATISTIC)
                   System.out.println("Can't compute the Minimum");
              else
                   System.out.println("the Maximum is:" + thisWork.getStatistics().getMaximum());
              if (thisWork.getStatistics().getAverage() == Statistics.CANT_COMPUTE_STATISTIC)
                   System.out.println("Can't compute the Average");
              else
                   System.out.println("the Average is:" + thisWork.getStatistics().getAverage());
              if (thisWork.getStatistics().getVariance() == Statistics.CANT_COMPUTE_STATISTIC)
                   System.out.println("Can't compute the Variance");
              else
                   System.out.println("the Variance is:" + thisWork.getStatistics().getVariance());
              if (thisWork.getStatistics().getStandardDeviation() == Statistics.CANT_COMPUTE_STATISTIC)
                   System.out.println("Can't compute the Standard Deviation");
              else
                   System.out.println("the Standard Deviation is:" + thisWork.getStatistics().getStandardDeviation());
    // OneStudentsExams.java for Lab 2
    // ICS 21 Fall 2002
    // OneStudentsWork is the exams and the statistics computed from
    // them that comprise one student's work
    class OneStudentsWork
         public static final int NUMBER_OF_EXAMS = 5;
         // The student is offered five exams...
         private Exam exam1;
         private Exam exam2;
         private Exam exam3;
         private Exam exam4;
         private Exam exam5;
         // The statistics on those exams
         Statistics studentStats;
         //                    -------------------- Constructor --------------------
         // Takes five constructed exam objects and store them for this student.
         // Constructs a statistics object that holds the stats for these exams and
         // store it in studentStats.
         public OneStudentsWork(Exam test1, Exam test2, Exam test3, Exam test4, Exam test5)
              // *** YOUR CODE GOES HERE ***
              exam1 = test1;
              exam2 = test2;
              exam3 = test2;
              exam4 = test4;
              exam5 = test5;
              studentStats = new Statistics(test1, test2, test3, test4, test5);
         //                    -------------------- Accessor methods --------------------
         // getExamX() methods make available ExamX
         public Exam getExam1()
              return exam1;
         public Exam getExam2()
              return exam2;
         public Exam getExam3()
              return exam3;
         public Exam getExam4()
              return exam4;
         public Exam getExam5()
              return exam5;
         // getStatistics() makes available the Statistics object that is part of this student's work
         public Statistics getStatistics()
              return studentStats;
    // Statistics.java for Lab 2
    // ICS 21 Fall 2002
    // A Statistics object stores the statistics for a group of Exams.
    class Statistics
         // This constant denotes a statistic that cannot be
         // computed, such as an average of zero scores or a variance
         // of one score.
         public static final int CANT_COMPUTE_STATISTIC = -9999;
         // The stats
         private int minimum;
         private int maximum;
         private int numberOfExamsTaken;
         private double average;
         private double variance;
         private double standardDeviation;
         //                    -------------------- Constructor --------------------
         // Calculates (initializes) the statistics, using passed-in exams.
         // Note that the order of computing thst stats matters, as some
         // stats use others; for instance, variance must be computed before
         // standard deviation.
         public Statistics(Exam exam1, Exam exam2, Exam exam3, Exam exam4, Exam exam5)
              // *** YOUR CODE GOES HERE ***
              calculateAverage(exam1,exam2,exam3,exam4,exam5);
              calculateVariance(exam1,exam2,exam3,exam4,exam5);
              calculateStandardDeviation(exam1,exam2,exam3,exam4,exam5);
         //                    -------------------- Accessor methods --------------------
         // getNumberOfExamsTaken() makes available the number of exams this student undertook
         public int getNumberOfExamsTaken()
              return numberOfExamsTaken;
         // getMinimum() makes the minimum available
         public int getMinimum()
              return minimum;
         // getMaximum() makes the maximum available
         public int getMaximum()
              return maximum;
         // getAverage() makes the average available
         public double getAverage()
              return average;
         // getVariance() make the variance available
         public double getVariance()
              return variance;
         // getStandardDeviation() make the standard deviation available
         public double getStandardDeviation()
              return standardDeviation;
         //                    -------------------- Statistics methods --------------------
         //     ---> Note: all statistics are to be computed using the number of exams taken
         // calculateNumberOfExamsTaken() computes the number of tests the student took
         // and stores the result in 'numberOfExamsTaken'
         // (Note this statistic can always be computed.)
         private void calculateNumberOfExamsTaken(Exam exam1, Exam exam2, Exam exam3, Exam exam4, Exam exam5)
              // *** YOUR CODE GOES HERE ***
              numberOfExamsTaken = OneStudentsWork.NUMBER_OF_EXAMS;
         // calculateMinimum() sets 'minimum' to the minimum score of exams taken, or
         // to CANT_COMPUTE_STATISTIC if a minimum can't be computed.
         private void calculateMinimum(Exam exam1, Exam exam2, Exam exam3, Exam exam4, Exam exam5)
              // *** YOUR CODE GOES HERE ***
              /*min = exam1.getScore();
              if (min > exam2.getScore())
                   min = exam2.getScore();
              if (min > exam3.getScore())
                   min = exam3.getScore();
              if (min > exam4.getScore())
                   min = exam4.getScore();
              if (min > exam5.getScore())
                   min = exam5.getScore();
              if(numberOfExamsTaken == 0)
                   minimum = CANT_COMPUTE_STATISTIC;
              else if(numberOfExamsTaken == 1)
                   minimum = exam1.getScore();
              else
                   minimum = exam1.getScore();
                   if(numberOfExamsTaken >= 2 && numberOfExamsTaken <= minimum)
                        minimum = exam2.getScore();
                   if(numberOfExamsTaken >= 3 && numberOfExamsTaken <= minimum)
                        minimum = exam3.getScore();
                   if(numberOfExamsTaken >= 4 && numberOfExamsTaken <= minimum)
                        minimum = exam4.getScore();
                   if(numberOfExamsTaken >= 5 && numberOfExamsTaken <= minimum)
                        minimum = exam5.getScore();
              if (getMinimum() == ExamsManager.ABSOLUTE_MIN_SCORE)
                   minimum = exam1.getScore();
                   //exam1.getScore() = getMinimum();
              else
                   exam1.getScore() = CANT_COMPUTE_STATISTIC;
         // calculateMaximum() sets 'maximum' to the maximum score of exams taken, or
         // to CANT_COMPUTE_STATISTIC if a maximum can't be computed.
         private void calculateMaximum(Exam exam1, Exam exam2, Exam exam3, Exam exam4, Exam exam5)
              // *** YOUR CODE GOES HERE ***
              /*if (maximum == ExamsManager.ABSOLUTE_MAX_SCORE)
              return true;
              else
              return CANT_COMPUTE_STATISTIC;*/
              max = exam1.getScore();
              if (max < exam2.getScore())
                   max = exam2.getScore();
              if (max < exam3.getScore())
                   max = exam3.getScore();
              if (max < exam4.getScore())
                   max = exam4.getScore();
              if (max < exam5.getScore())
                   max = exam5.getScore();
              if(numberOfExamsTaken == 0)
                   maximum = CANT_COMPUTE_STATISTIC;
              else if(numberOfExamsTaken == 1)
                   maximum = exam1.getScore();
              else
                   maximum = exam1.getScore();
                   if(numberOfExamsTaken >= 2 && numberOfExamsTaken >= maximum)
                        maximum = exam2.getScore();
                   if(numberOfExamsTaken >= 3 && numberOfExamsTaken >= maximum)
                        maximum = exam3.getScore();
                   if(numberOfExamsTaken >= 4 && numberOfExamsTaken >= maximum)
                        maximum = exam4.getScore();
                   if(numberOfExamsTaken >= 5 && numberOfExamsTaken >= maximum)
                        maximum = exam5.getScore();
         // calculateAverage() computes the average of the scores for exams taken and
         // stores the result in 'average'. Set to CANT_COMPUTE_STATISTIC if there
         // are no tests taken.
         private void calculateAverage(Exam exam1, Exam exam2, Exam exam3, Exam exam4, Exam exam5)
              // *** YOUR CODE GOES HERE ***
              if (numberOfExamsTaken == 5)
                   average = (exam1.getScore()+exam2.getScore()+exam3.getScore()+exam4.getScore()+exam5.getScore()/OneStudentsWork.NUMBER_OF_EXAMS);
              else if (numberOfExamsTaken == 4)
                   average = (exam1.getScore()+exam2.getScore()+exam3.getScore()+exam4.getScore()/OneStudentsWork.NUMBER_OF_EXAMS);
              else if (numberOfExamsTaken == 3)
                   average = (exam1.getScore()+exam2.getScore()+exam3.getScore()/OneStudentsWork.NUMBER_OF_EXAMS);
              else if (numberOfExamsTaken == 2)
                   average = (exam1.getScore()+exam2.getScore()/OneStudentsWork.NUMBER_OF_EXAMS);
              else if (numberOfExamsTaken == 1)
                   average = (exam1.getScore()/OneStudentsWork.NUMBER_OF_EXAMS);
              else if (numberOfExamsTaken == 0)
                   average = CANT_COMPUTE_STATISTIC;
         // calculateVariance() calculates the returns the variance of the
         // scores for exams taken and stores it in 'variance'
         // For a small set of data (such as this one), the formula for calculating variance is
         // the sum of ((exam score - average) squared) for scores of exams taken
         // divided by (the number of scores - 1)
         // Set to CANT_COMPUTE_STATISTIC if there are fewer than two tests taken.
         private void calculateVariance(Exam exam1, Exam exam2, Exam exam3, Exam exam4, Exam exam5)
              // *** YOUR CODE GOES HERE ***
              if (numberOfExamsTaken == 5)
                   variance = ((exam1.getScore()-average)*(exam1.getScore()-average)+(exam2.getScore()-average)*(exam2.getScore()-average)+(exam3.getScore()-average)*(exam3.getScore()-average)+(exam4.getScore()-average)*(exam4.getScore()-average)+(exam5.getScore()-average)*(exam5.getScore()-average))/4;
              else if (numberOfExamsTaken == 4)
                   variance = ((exam1.getScore()-average)*(exam1.getScore()-average)+(exam2.getScore()-average)*(exam2.getScore()-average)+(exam3.getScore()-average)*(exam3.getScore()-average)+(exam4.getScore()-average)*(exam4.getScore()-average))/4;
              else if (numberOfExamsTaken == 3)
                   variance = ((exam1.getScore()-average)*(exam1.getScore()-average)+(exam2.getScore()-average)*(exam2.getScore()-average)+(exam3.getScore()-average)*(exam3.getScore()-average))/4;
              else if (numberOfExamsTaken == 2)
                   variance = ((exam1.getScore()-average)*(exam1.getScore()-average)+(exam2.getScore()-average)*(exam2.getScore()-average))/4;
              else if (numberOfExamsTaken < 2)
                   variance = CANT_COMPUTE_STATISTIC;
         // calculateStandardDeviation() calculates the standard
         // deviation of the scores of taken exams and stores
         // it in 'standardDeviation'
         // The formula for calculating standard deviation is just
         // the square root of the variance
         private void calculateStandardDeviation(Exam exam1, Exam exam2, Exam exam3, Exam exam4, Exam exam5)
              // *** YOUR CODE GOES HERE ***
              if (variance == CANT_COMPUTE_STATISTIC)
                   standardDeviation = CANT_COMPUTE_STATISTIC;
              else
                   standardDeviation = (Math.sqrt(variance));
    // Exam.java for Lab 2
    // ICS 21 Fall 2002
    // An Exam object stores information about one exam
    class Exam
         private boolean examTaken;     //was the exam taken? true for yes, false for no
         private int score;               //the exam's score; = 0 if test not taken
         //                    -------------------- Constructors --------------------
         // Construct a taken exam; it has score 's'
         public Exam(int s)
              score = s;
              examTaken = true;
         // Construct an exam not taken; it has a score of 0
         public Exam()
              score = 0;
              examTaken = false;
         //                    -------------------- Accessor methods --------------------
         // Make the score of an exam available
         public int getScore()
              return score;
         // Make available whether an exam was taken
         public boolean wasTaken()
              return examTaken;

    Your code is absolutely unreadable - even if someone was willing to
    help, it's simply impossible. I do give you a few tips, though: If you
    understand your code (i.e. if it really is YOUR code), you should be
    able to realize that your minimum and maximum never get set (thus they
    are both 0) and your exam 3 is set with the wrong value. SEE where
    those should get set and figure out why they're not. Chances are you
    are doing something to them that makes one 'if' fail or you just
    erroneously assign a wrong variable!

  • Classes and Global Data

    OK, I've been battling how to do this with my test code and now it comes back to "bite" me in my new project.
    In regular C, you just create your structures, fill them with data, and then your subroutines have full access to the global data.
    With Objective-C you envelop certain data inside other objects. I got that. In fact, that's where I've gotten "stuck". Let me elaborate.
    I have a the following classes:
    Class (number of instances expected) description of class
    Scenes (1) tables containing dictionaries of scenes and scene components
    Pieces (1) tables containing images, type specs, etc. of game pieces
    Blocks (1) tables with definitions, specs of movable game pieces
    MainView (1) main application view, contains methods to draw the main gameboard
    BlockView (n) view for the block and data needed to manipulate it by the main game logic
    MainViewController (1) main controller for game screen
    Ok, since MainView manages the game window it's init methods also call the init methods to instantiate the one instance of Scenes and Pieces which are needed to be setup in order for MainView to draw the currentScene using the UIImage figures for each of the pieces. So, it saves a pointer to the Scenes and Pieces instances. MainViewController can access those since it sets up MainView and has a pointer to it. MainViewController is currently where I had planned on firing up the BlockView subviews, one for each movable game blocks.
    The problem comes with BlockView which has the logic to setup the additional data for each block type, but does not have a pointer to the instances of Scenes or Pieces which contain the current scene info and the UIImage dictionary to use for drawing the actual images on the screen. How can it get a pointer to the appropriate classes?
    Since BlockView is invoked by MainViewController as it sets up the pieces, I could pass the pointer as part of the init method, but that seems like the WRONG place. Shouldn't I be able to put some block of pointers someplace where all objects can query to get the data needed (keeping it encapsulated within some master gameSettings object).
    Actually that's part of where I'm going with this. I want to have a settings object which knows what scene is current, what block set (images) is in use (so I can have different images for each piece depending on which set is selected), and the saved state information needed to continue where I left off. (This part is mostly a serialization of the Blocks instances which contain both the initial and current locations on the screen, and the current background tableau which shows a more-or-less static background for each scene).
    Instead of one object, right now I've separated the types of information by 3 classes, but everything needs access to two of those classes in order to fully function. I think I have that part under control. What I don't have is the BlockView instances and the GameLogic methods having access to the Scenes and Pieces data unless I pass a pointer to them during initialization.
    Is that what I'm supposed to do?
    Or is there a better way?
    Lastly, my game logic is really a set of methods which act on ONE specific piece to move it, but then that movable piece (one of the instances of BlockView) is able to push other pieces as it moves. Additional methods will handle the pushing of the other instances of BlockView around until a solution is completed for the scene. That part, I think I've gotten OK, as the game logic will be Built into the Blocks or BlockView classes. (That's the part I will have to figure out).
    I'm adding this to my query, so you know my intention, and whether I'm on the right track. So far my Blocks class only contains definitions used by BlockView, and no instance variables or methods yet. If all the logic can be put into the BlockView methods, I can probably throw Blocks away.
    So, do I add a pointer to my init method...
    - (id)initWithString:(NSString*)myType atPoint:(CGPoint)point
    becomes
    - (id)initWithString:(NSString*)myType atPoint:(CGPoint)point inScene:(Scene)scene ofSet:(Pieces)pieceSet
    If that is what it takes, I can do it. It just seems there ought to be a better way.
    Of course, I could abstract those last pointers to only provide the pieces needed for that one instantiation of a BlockView, as I have with 'myType' and 'point' by supplying only the 'pieceSet' to init, but then the game logic will need to have access to the 'scene' to know whether a given block is allowed to move to a given position. This is where I get confused as far as what information to pass to a class, since I know other methods invoked by touches will cause the blocks (in BlockView instances) to move around on the screen displayed by MainView.
    Actually MainView will be detecting the touches and moving the instances of BlockView, so maybe the game logic SHOULD be in MainView instead. I just figured that to encapsulate it as methods that operate on the movable pieces, the methods should be in BlockView, and called by the touch detection routines in MainView.
    Comments please. And don't say, you can do it either way... one way or the other, or yet a third way I don't fully comprehend (such as another viewController) should contain the logic. I think the logic is part of the model and not the view, but in this case, it affects the view based on the background squares and what happens to each block as it is moved or pushed "into" one of those squares.
    Thanks in advance. I realize this may be a complicated question, but I think it is a fairly BASIC question, and my lack of Objective-C experience is showing.
    To tie the question up a little better, I'm not expecting to have all objects have complete access to lots of global data. What I'm looking for is a place to put a pointer to each of my classes which are only ever instantiated once, and have that pointer be findable by any other class that can then query the appropriate class instance to retrieve the data. Right now, I have one and only one place holding these pointers, and am passing them to the objects/classes which need access to the data in those Scene and Pieces classes when they need them.
    If that is the way I'm supposed to do it, then I'm on the right track, even if it means deciding which classes are allowed to hold and pass the appropriate object pointers to other objects.

    etresoft wrote:
    I think you are missing an important piece - the "model" - from the MVC architecture - Model, View, Controller.
    Your "business logic" is composed of your Scenes, Pieces, and Blocks. That is your model. Your view shouldn't really know anything about that. Your controller understands both your model and your view and it puts the two together to draw things. You want to be able to swap our your GUI view for a text view, if you wanted to. Chess, for example, can be played in a GUI or from a text console. A more modern example is a multiplayer game. It has to function across a network so its model has to be projected to the local display as well as sent across the network.
    Yes, I am still fighting with understanding the implementation of some concepts.
    What I think I am wanting to do, is similar to what Apple has done with the file manager or notification centers, and be able to request information from my model as needed.
    For example, my view doesn't care about the specifics of the scenes or pieces, yet my view wants to be able to display the name of the current scene or display the correct image for a piece. Right now, it keeps an instance pointer to my "singleton" Scene object, and using the scene index, gets the current name. To display images, it gets those from the Pieces singleton's image dictionary, and again keeps a pointer to do that.
    What I would rather do is be able to get that pointer for the views that need it without having to copy it, or have back pointers to the superview which holds a copy of those pointers. My BlockView class layers the active pieces over the MainView which holds the playing board. To access things, my code looks like:MainView* mainView = (MainView*) self.superview;
    NSString* key = [mainView.myScene.sceneKeys objectAtIndex:mainView.currentSceneIndex];
    NSString* pieceName = [[mainView.myScene.scenes objectForkey:key] pieceAtLocation:loc];
    UIImage* image = [mainView.myPieces.images objectForkey:pieceName];
    Oh, and this isn't actual code. It is a contrived example. I have since made it more efficient.
    What I think would be more appropriate would be something like this:
    NSString* pieceName = [[Scenes CurrentScene] pieceAtLocation:loc];
    UIImage* image = [[Pieces PieceImages] objectForkey:pieceName];
    or even
    UIImage* image = [[Pieces PieceImages] objectForKey:[[Scenes CurrentScene] pieceAtLocation:loc]];
    When I attempt to create class methods to access data in my "singleton", I get lots of warnings about accessing instance data in a class method. So, instead I made everything an instance method, but that requires keeping a pointer to the instance available somewhere.
    I have been able to recode some of the instance methods which manipulate derived strings from the instance data into class methods, but not the data read in from the plist data files.
    What I'm missing is how to get the current "singleton" instance from the class, and then use that as the instance pointer, i.e. in the examples above, I guess that pieceAtLocation: would be an instance method, but CurrentScene and PieceImages would be class methods that return an instance pointer to the appropriate dictionaries. How to implement that correctly is where I'm still sketchy.
    Isn't that how Apple has defined DefaultNotificationCenter or DefaultFileManager?
    I've looked at some singleton code, and am not sure how it helps me get this done, so an example would definitely help.

Maybe you are looking for

  • Error while authenticating a user

    Dear all, Hope you all are doing well. Production issue : When an user tries to login with his username and password. He is getting error message "INTERNAL ERROR OCCURED". And the standard RFC which i'm using for authenticating user is  SUSR_LOGIN_CH

  • ACR122U smart card reader not recognized after reboot...

    I am new to POS Windows and have been working with wondows for ever. I was using ACR 122u contactless usb smart card reader with windows XP and communicating with it using java with no problems. Then our I changed the OS to windows Pos ready 2009 and

  • Mail not showing new account

    Hi there! I have added a new account (IMAP) and successfully configured it with an automatic installer provided by the hosting service. I can see the new account only in the inbox folder, but not in the other folders (Sent, Trash, Junk, Drafts). How

  • Resolving ip addresses from an iPad

    Hi, I've been given an iPad 3 (wifi version) for work and I'm having trouble getting it to resolve names correctly. I've connected it to a wireless access point and I can navigate around our LAN via IP addresses, but we have a number of web products

  • XML String

    i want to fatch each node string of xml file.just like if my xml file is given below then <ROWSET> <ROW num="1"> <CUSTOMER> <CUSTOMERID>1044</CUSTOMERID> <FIRSTNAME>Paul</FIRSTNAME> <LASTNAME>Astoria</LASTNAME> <HOMEADDRESS> <STREET>123 Cherry Lane</