Accessor methods

Hello,
I am working on a temp class that has 2 instance variables, double tempValue, and char tempScale ('C' or 'F').
My constructor methods are working fine. My mutator (set) methods are working fine.
I need to write two accessor methods, one that returns the temp in Fahrenheit, and one that returns the temp in Celsius.
I am not sure how to return both the tempValue and the tempScale for both of these methods. Here is my starting point:
//accessor method to return the degrees Fahrenheit.
public double getF()
return tempF;     //tempF = (9*(tempC)/5 + 32)
//accessor method to return the degrees Celsius
public double getC()
return tempC;     //tempC = 5*(tempF - 32)/9
}Thank you,
Eric

If possible, I would like to stick to the program I am working on. It is much easier for me to understand.
Is there any way you can just use my program as the example?
Here is what I have so far:
public class TestTemp
//Two parameters, a temperature value (a floating-point number)
//and a character for the scale, either 'C' for Celsius or 'F'
//for Fahrenheit.
private double tempValue;     //in degrees
private char tempScale;     //in either 'C' or 'F'     
public void writeOutput()
System.out.println("The temperature is " + (tempValue) + " degrees " + tempScale + ".");
//Four constructor methods, one for each instance variable,
//(assume zero degrees if no value isspecified and Celsius
// if no scale is specified), one with two parameters for the
//two instance variables, and a default constructor (set to
//zero degreees Celsius.
//constructor method for the instance variable tempValue
public TestTemp(double initialTempValue)
tempScale = 'C';
if(initialTempValue < 0)
System.out.println("Error:  Negative temperature value.");
System.exit(0);
else
round(initialTempValue);
tempValue = initialTempValue;
//constructor method for the instance variable tempScale
public TestTemp(char initialTempScale)
tempValue = 0;
initialTempScale = Character.toUpperCase(initialTempScale);
if(initialTempScale == 'C' || initialTempScale == 'F')
tempScale = initialTempScale;
else
System.out.println("Error:  Must be C or F.");
System.exit(0);
//constructor method for both instance variables tempValue and tempScale
public TestTemp(double initialTempValue, char initialTempScale)
if(initialTempValue < 0)
System.out.println("Error:  Negative temperature value.");
System.exit(0);
else
round(initialTempValue);
tempValue = initialTempValue;
initialTempScale = Character.toUpperCase(initialTempScale);
if(initialTempScale == 'C' || initialTempScale == 'F')
tempScale = initialTempScale;
else
System.out.println("Error:  Must be C or F.");
System.exit(0);
//default constructor method
public TestTemp()
tempValue = 0.0;
tempScale = 'C';     
//Two accessor (get) methods, one to return the degrees Celsius,
//and one to return the degrees Fahrenheit.
//Round to the nearest tenth of a degree.
//accessor method to return the degrees Fahrenheit.
public double getF()
if(tempScale == 'F')
System.out.println("Error:  The temp scale is already Fahrenheit.");
return 0;
else
double tempF;
tempF = ((9 * tempValue)/5 + 32);  //tempF = ((9*tempC)/5 + 32)
tempValue = tempF;
tempScale = 'F';
round(tempValue);
return tempF;          
//accessor method to return the degrees Celsius
public double getC()
if(tempScale == 'C')
System.out.println("Error:  The temp scale is already Celsius.");
return 0;
else
double tempC;
tempC = (5 * (tempValue - 32)/9);          //tempC = 5*(tempF - 32)/9
tempValue = tempC;
tempScale = 'C';
round(tempValue);
return tempC;     
//round method returns the tempValue rounded to tenths
public double round(double roundTempValue)
tempValue = Math.round(tempValue * 10.0)/10.0;
return tempValue;
//Three reset methods, one to reset the value, one to reset the
//scale ('F' or 'C'), and one to reset both the value and the scale.
//reset method to reset tempValue
public void set(double newTempValue)
if(newTempValue < 0)
System.out.println("Error:  Negative temperature value.");
System.exit(0);
else
round(newTempValue);
tempValue = newTempValue;
//tempScale is unchanged
//reset method to reset tempScale
public void set(char newTempScale)
newTempScale = Character.toUpperCase(newTempScale);
if(newTempScale == 'C' || newTempScale == 'F')
tempScale = newTempScale;
else
System.out.println("Error:  Must be C or F.");
System.exit(0);
//tempValue is unchanged
//reset method to reset tempValue and tempScale
public void set(double newTempValue, char newTempScale)
if(newTempValue < 0)
System.out.println("Error:  Negative temperature value.");
System.exit(0);
else
round(newTempValue);
tempValue = newTempValue;
newTempScale = Character.toUpperCase(newTempScale);
if(newTempScale == 'C' || newTempScale == 'F')
tempScale = newTempScale;
else
System.out.println("Error:  Must be C or F.");
System.exit(0);
//tempValue and tempScale are reset
//Driver program that tests all the methods.
//Use each one of the constructors.
//Include at least one true and one false
//case for each of the comparison methods.
//Test the following: 
//          0.0 degrees C = 32 degrees F
//          -40 degrees C = -40 degrees F
//          100 degrees C = 212 degrees F     
public class TestTempDriver
public static void main(String[] args)
//t1, t2, t3, and t4 test the four constructors
TestTemp t1 = new TestTemp();
t1.writeOutput();
TestTemp t2 = new TestTemp(22.222);
t2.writeOutput();
TestTemp t3 = new TestTemp('f');
t3.writeOutput();
TestTemp t4 = new TestTemp(44.444, 'f');
t4.writeOutput();
//t5 tests the set method with both the double and char parameters
TestTemp t5 = new TestTemp(55.555, 'f');
System.out.println("The initial temp for t5 is:");
t5.writeOutput();          
System.out.println("Please enter the correct temp:");
double correctTemp = SavitchIn.readLineDouble( );
System.out.println("Please enter the correct temp scale:");
char correctScale = SavitchIn.readLineNonwhiteChar( );
t5.set(correctTemp, correctScale);
System.out.println("The updated temp for t5 is:");
t5.writeOutput();          
//t6 tests the set method with the double parameter
TestTemp t6 = new TestTemp(66.666, 'f');
System.out.println("The initial temp for t6 is:");
t6.writeOutput();
System.out.println("Please enter the correct temp:");
correctTemp = SavitchIn.readLineDouble( );
t6.set(correctTemp);
System.out.println("The updated temp for t6 is:");
t6.writeOutput();
//t7 tests the set method with the char parameter
TestTemp t7 = new TestTemp(77.777, 'f');
System.out.println("The initial temp for t7 is:");
t7.writeOutput();
System.out.println("Please enter the correct temp scale:");
correctScale = SavitchIn.readLineNonwhiteChar( );
t7.set(correctScale);
System.out.println("The updated temp for t7 is:");
t7.writeOutput();
//t8 tests the getF accessor method
TestTemp t8 = new TestTemp();     
double convertTemp = 88.888;
char convertScale = 'c';
t8.set(convertTemp, convertScale);
t8.getF();     
t8.writeOutput();
//t9 tests the getC accessor method
TestTemp t9 = new TestTemp();
convertTemp = 99.999;
convertScale = 'f';
t9.set(convertTemp, convertScale);
t9.getC();     
t9.writeOutput();
}Thanks,
Eric

Similar Messages

  • Using mutator and accessor methods in main.

    Would somebody explain to me exactly how mutator and accessor methods make a class and it's driver program work together. I understand the principle of encapsulation, but I'm obviously missing something. I get the syntax, but what actually happens? I'm hoping a fresh perspective on it will help me understand better.
    I guess another way to ask the question could be: how do you use accessor and mutator methods in the main program that calls them?

    >
    the assignment says to have a
    "reasonable set of accessor and mutator methods
    whether or not you use them". So in my case I have
    them written in the class but do not call them inthe
    driver program. And like I said, the program does
    what it's supposed to do.This class you're in worries me. I'm sure what
    polytropos said is true: they're trying to make you
    think about reuse. But adding to an API without cause
    is widely considered to be a mistake, and there are
    those who are strongly opposed to accessors/mutators
    (or worse, direct field access) on OOP design grounds.The class is based on the book Java: Introduction to Computer Science and Progamming, by Walter Savitch. Until now I've been pretty happy with it. Another problem, to me anyway, is that so far we've done a few, cumulative programming projects per chapter. This time, there was one assignment for the whole chapter that is suppsoed to incorporate everything. But that's just me complaining.
    Here is the code I have and that it looks like I'll be turning in... criticisms welcome.
    Here is the class:
    public class GradeProgram//open class
         private double quiz1;
         private double quiz2;
         private double mid;
         private double fin;
         private double finalGrade;
         private char letterGrade;
         public void readInput()//open readInput object
              do
                   System.out.println("Enter the total points for quiz one.");
                   quiz1 = SavitchIn.readLineInt();
                   System.out.println("Enter the total points for quiz two.");
                   quiz2 = SavitchIn.readLineInt();
                   System.out.println("Enter the mid term score.");
                   mid = SavitchIn.readLineInt();
                   System.out.println("Enter final exam score.");
                   fin = SavitchIn.readLineInt();
                   if ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0))
                   System.out.println("Quiz scores are between one and ten.  Re-enter scores");
                   if ((mid>100)||(fin>100)||(mid<0)||(fin<0))
                   System.out.println("Exam scores are between zero and one hundred.  Re-enter scores.");
              while ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0)||(mid>100)||(fin>100)||(mid<0)||(fin<0));
         }//end readInput object
         public void output()//open output object
              System.out.println();
              System.out.println("You entered:");
              System.out.println("Quiz 1: " + (int)quiz1);
              System.out.println("Quiz 2: " + (int)quiz2);
              System.out.println("Mid term: " + (int)mid);
              System.out.println("Final exam: " + (int)fin);
              System.out.println();
              System.out.println("Final grade: " + (int)percent() + "%");
              System.out.println("Letter grade: " + letterGrade());
         }//end output object
         public void set(double newQuiz1, double newQuiz2, double newMid, double newFin, double newFinalGrade, char newLetterGrade)
              if ((newQuiz1 >= 0)&&(newQuiz1 <= 10))
              quiz1 = newQuiz1;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newQuiz2 >= 0)&&(newQuiz2 <= 10))
              quiz2 = newQuiz2;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newMid >= 0)&&(newMid <= 100))
              mid = newMid;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              if ((newFin >= 0)&&(newFin <= 100))
              fin = newFin;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              letterGrade = newLetterGrade;
         public double getQuiz1()
              return quiz1;
         public double getQuiz2()
              return quiz2;
         public double getMid()
              return mid;
         public double getFin()
              return fin;
         public char getLetterGrade()
              return letterGrade;
         private double finalPercent()//open finalPercent object
              double quizPercent = (((quiz1 + quiz2) /2) * 10) / 4;
              if (((((quiz1 + quiz2) /2) * 10) % 4) >= 5)
                   quizPercent++;
              double midPercent = mid / 4;
              if ((mid % 4) >= 5)
                   midPercent++;
              double finPercent = fin / 2;
              if ((fin % 2) >= 5)
                   finPercent++;
              finalGrade = (quizPercent + midPercent + finPercent);
              return (finalGrade);
         }//end final percent object
         private double percent()//open percent object - helping object
              double percentGrade = finalPercent();
              return (percentGrade);
         }//end percent object
         private char letterGrade()//open letterGrade object
              double letter = percent();
              if (letter >= 90)
                   return ('A');
              else if (letter >= 80)
                   return ('B');
              else if (letter >= 70)
                   return ('C');
              else if (letter >= 60)
                   return ('D');
              else
                   return ('F');
         }//end letterGrade object
         private double quizScore()//open quizScore object
              double quizes = ((quiz1 + quiz2) /2) * 10;
              return (quizes);
         }// close quizScore object
    }//end classAnd here is the driver program:
    public class GradeProgramDemo
         public static void main(String[] args)
              String cont;
              do
                   GradeProgram firstStudent = new GradeProgram();
                   firstStudent.readInput();
                   firstStudent.output();
                   System.out.println();
                   System.out.println("Enter more student grades?  Enter Y to continue");
                   System.out.println("or press enter to quit.");
                   cont = SavitchIn.readLine();
                   System.out.println();
              while (cont.equalsIgnoreCase("y"));

  • Problem exposing Accessor Methods on View object (ViewRowImpl.java)

    JDeveloper 9.03
    I have a view link, ViewLinkSourceDest, that links two view objects Source and Destination. Each view object has its respective ViewRowImpl.java file created.
    I have selected "Generate Accessor in View Object" in View link Properties of the View Link Wizard for both source and destination view objects.
    The correct Accessor methods are available in both the source and destination ViewRowImpl files.
    When I access the Source accessor method from the DestinationViewRowImpl object I receive the following error:
              ORA-00904: invalid column name
              It is also is displaying the Source view object's SQL statement with the (:1 = Destination.ID) where clause.
    The error is occurring when trying to retrieve the view object using this type of method call:
              Row r = this.getSourceView();
    After further investigation I have found an example set of view objects in which the error does not occur. The difference was in the ViewLink.xml file.
    The ViewLink.xml file that accesses the Accessor with the error begins like this:
              <ViewLink     
                   Name="ViewLink"
                   Where=":1 = Destination._ID" >
    The ViewLink.xml file that accesses the Accessor with no error begins like this:
              <ViewLink     
                   Name="ViewLink"
                   EntityAssociation ="SourceDestAssociation" >
    suggesting that the use of an association would resolve this problem.
    I was not able to create a View link based on an association that would generate a ViewLink.xml file that ressemble the successful file above. I could however manually add the correct entry to the xml file that caused the error and sucessfully access the Accessor method in the source object. This is not the final answer because the IDE will regenerate the ViewLink.xml file to its original state even if created with the appropriate Association.
    Is this a bug?
    Is the way the ViewLink.xml file created different in JDev 9.03 than in 9.02
    Is there something I am missing that is causing the ViewLink.xml file to generate incorrectly?
    Any suggestions would be helpful.
    Rob

    Steps to recreate:
    1 Create SomeSuperEntityImpl.java extended by SourceEntityImpl.java and DestinationEntityImpl.java entity objects.
    2 Create SourceView and DestinationView objects
    3 Create SourceDestinationAssociation linking the entity object Source PK to Destination FK
    4 Create SourceDestinationView linking Source and Destination view using the SourceDestinationAssociation
    View the SourceDestinationView.xml file and you will see that the viewlink has Where=":1 = source.src_id"
    This is the scenario that causes the initial problem with the Accessor Methods.
    If the SomeSuperEntityImpl.java is removed as the super class and the same procedure is followed you will get the desired 'EntityAssociation = "package.SourceDestinationAssociation"' in the SourceDestinationView.xml file .
    Hope this is a little clearer.
    Rob

  • Public instance variable vs. accessor method

    I know some OOP purists believe all instance variables should be private, and if there's a need to view or set the value of these instance variable, public accessor methods need to be created. Data encapsulation is the driving force behind this belief.
    But in Java, it's easy enough to declare an instance variable public thus eliminating the need to write accessor method. What's the rational behind this feature? Is it merely to save developer some time from typing in the accessor methods? Does this reason justify the use of public members?

    I know some OOP purists believe all instance variables
    should be private, ALL? No way!
    and if there's a need to view or
    set the value of these instance variable, public
    accessor methods need to be created. There has to be a reason for any :- public int getMyInt(){ ...
    and in many cases protected or default package is more appropriate
    Data
    encapsulation is the driving force behind this belief.
    Correct , also avoiding multiple instances of member states - very often its a control issue too
    But in Java, it's easy enough to declare an instance
    variable public Yes and its also easy enough to write shittie code too ...
    if an instance variable is public there should be a clear comment explaining why the field has to be public
    thus eliminating the need to write
    accessor method. There's nothing wrong with accessors and mutators - the java language is full if them
    What's the rational behind this
    feature? As you stated encapsulation
    Is it merely to save developer some time
    from typing in the accessor methods? This is a lame reason
    Does this reason
    justify the use of public members?and attract unwanted side effects?
    I also don't like to see (or to write) a huge long list of getters and setters at the bottom of any class file and find it quite ugly - You should use them when you need to, not as a matter of routine.
    Accessor - mutator is a design issue for private instance variables that you wish to keep hidden. Your suggestion to make them all public is also a design issue and if I was to see a long list of public variables at the beginning of a class (unexplained with javadoc comments) I would be very puzzled indeed.
    Eclipse will automate the generation of accessors and mutators for you and also has a refactoring tool too - both are extremely useful

  • Multi-Threaded gui components and accessor methods

    hello, I'm working on a small gui component which makes use of swingworker to deal with time consuming methods.
    My question is what is the best way to handle accessor methods for example to tackle the following code scenario:
    MyComponent myComponent = new MyComponent();
    myComponent.render(); // long task handed out to a thread
    myComponent.getVariable(); // will only return correct value if render() has completed
    Is the best option to use a Listener and fire a 'render completed' event?
    Thanks for any ideas,
    bm

    I think that's good approach to go with.
    Sai Pullabhotla.

  • Constructor, accessor methods

    Hi,
    I have read some codes examples from book, one code made direct references to instance variables from inside client
    implementations (e.g., emp.employeeid) - instead of using accessor
    methods. And the book actually suggests using accessor methods.
    Why it is better to use constructors, accessor, and mutator methods on private instance variables?
    I am not very clear on this concept, why accessor or mutator methods are better ?
    I think the book implies emp.getEmployeeid() is the better approach, am I right ? but why ?
    Thanks in advance !
    Phil

    Thanks ! But, I can do something like this..
    class Department {
    Employee emp = new Employee();
    int id = emp.employeeid;
    It looks ok, isn't it ?Only if employeeid is a public variable. If it is marked private in the Employee class then it won't work.
    Another reason for using accessor and mutator methods is so that the author of the class can have control over how the private variables are used and to trap bad values.
    If the variables are left public then the data contained in them could be corrupted by another class manipulating them. Making the variable private and having a mutator method allows more control over what gets stored in the variable.

  • LV OOP when using accessor methods (subVIs) or bundle/unbundle operation?

    Hello
    When should I use the (private) accessor methods (subVIs) and when the bundle/unbundle operation to access the class data? What is the reason that the bundle/unbundle operation is introduced to LabVIEW OOP? I need some rules for a coding guideline.
    Thanks
    Solved!
    Go to Solution.

    Thanks for your hints. I wanted to understand the differences between a private vi access and the unbundle operation like in the picture.
    I found some more explanations on the website: http://www.ni.com/white-paper/3574/en
    -> "Creating "read" and "write" methods for every data value in a class is a process acknowledged to be cumbersome. LabVIEW 8.5 introduced the ability to create accessor VIs from a wizard dialog, and LV2009 added further options to that dialog.
    We were concerned about the performance overhead of making a subVI call instead of just unbundling the data. We found that our current compiler overhead for the subVI call is negligible (measured between 6 and 10 microseconds on average PC). A bundle/unbundle operation directly on the caller VI versus in a subVI is nearly the same amount of time. We do have an issue with data copies for unbundled elements because much of LabVIEW's inplaceness algorithm does not operate across subVI boundaries. As a workaround, you may also choose to avoid accessor methods in favor of methods that actually do the work in the subVI to avoid returning elements from the subVI, thus avoiding data copies. This choice is frequently better OO design anyway as it avoids exposing a class' private implementation as part of its public API. In future versions, we expect that inlining of subVIs will become possible, which will remove the overhead entirely.  
    We feel in the long term it is better to improve the editor experience and the compiler efficiency for these VIs rather than introducing public/protected/community data."

  • Publicizing controls vs  accessor methods

    hi. this might be a stupid question but i really want to knw why i should avoid declaring controls such as textboxes, buttons, etc.. as public instead of using accessor methods to modify its properties from a different class. i was wondering if anyone could give me the "real world" justification for it and not just give me a textbook answer. thanks.

    I asked that question because I found the following one on the example of mock:
    A class can not be called "tightly encapsulated" unless which of the following is true?
    a.      All member fields are declared final.
    b.      The class is not anonymous.
    c.      The internal data model can be read and modified only through accessor and mutator methods.
    d.      The class is an inner class.
    e.      None of the above
    I think it would be found in:
    Section 5: OO Concepts
    all right?

  • I'm confused about accessor methods.

    Part of the application I'm developing translates a sequence of strings into a series of hex values. The number of strings will be either 2 or 3. In the cass where there's 3 strings the last would represent an integer or a decimal fraction.
    I have a class Xlate that has 3 translation methods thus:
    public int[] translate(String msg) {};
    public int[] translate(String msg, int val) {};
    public int[] translate(String msg, String aValString) {};
    The problem I have is that the Xlate does not return what is expected when passed an argument via the method signature. If explicitly passed a string sequence it works OK.
    If I pass the argumants... "pause" "21.09876"
    I would expect to see a translation of ... "msg translation array = 76,98,10,20,0A"
    What I get is "msg translation array = FF, FF, FF, FF,FF" which indicates the array has not been amended after initialised.
    This is most likely due to the lack of accessor definitions and their use. HOWEVER, I am confused by such methods.
    I now realise that to pass values setter/getter accessor methods are .
    I think these might be along the lines of the following:
    private String[] commandList; // declares a string variable
    public Xlate() { this(""); }
    public Xlate(String[] msg) { this.commandList = msg[1]; } // holds the name
    public String getCommandStrings() { return this.commandList; } // gets the commandList
    I can't get this to work and know these are not correct.
    I need help to get me moving ahead of this problem. Any help would be appreciated.
    Thanks.
    Philip
    import java.lang.String;
    public class Control {
      public Control() {
       int i;
      static final public Xlate x = new Xlate();
    //  static final public Comms rc = new Comms();
      public static void main(String[] args) {
        String cmd[] =  args;
        for (int i=0;i<args.length;i++)
          cmd=args[i];
    controller(cmd);
    // public static void controller(String portName, String command, String parameter) {
    public static void controller(String[] parameters) {
    Control c = new Control();
    int[] msg ={1,1,1,1,1};
    // Booleans 'pragmaN' are used to select/deselect debug statements
    // though would be embedded in the bytecode
    // so these are not compiler directives
    boolean pragma1=true, pragma2=true, pragma3=true; // toggle using !
    int pVal;
    if (pragma1==true) {
    System.out.print("msg array = ");
    for (pVal=0; pVal<4;pVal++)
         System.out.print(Integer.toHexString(msg[pVal]).toUpperCase() + ",");
    System.out.println(Integer.toHexString(msg[pVal++]).toUpperCase());
    // rc.setupComPort(parameters[0]); // Configure the port referenced
    msg = x.translate("start"); //*********TRANSLATE()************
    msg = x.translate("pause","12.34567"); //*********TRANSLATE()************
    if (pragma2==true) {
    System.out.print("msg translation array = ");
    for (pVal=0; pVal<4;pVal++)
         System.out.print(Integer.toHexString(msg[pVal]).toUpperCase() + ",");
    System.out.println(Integer.toHexString(msg[pVal++]).toUpperCase());
    // rc.writeCmd(msg);
    // Control messages have 3 fixed formats comprising 'a string', 'a string
    // plus an integer' and 'a String plus a String'.
    // For the control messages with an argument a string is constructed before
    // translation by parging the arguments.
    // Do ensure the number of args is greater than 1 and less than 3.
    // Converts integer types to Strings
    String argString="";
    System.out.println("arg len = "+ parameters.length);;
    switch (parameters.length) {
    case 2:
         System.out.println("in switch 2");;
         argString = (parameters[1]);
         msg = x.translate(argString); //*********TRANSLATE()************
         if (pragma3==true) {
         System.out.print("msg translation array = ");
         for (pVal=0; pVal<4;pVal++)
         System.out.print(Integer.toHexString(msg[pVal]).toUpperCase() + ",");
         System.out.println(Integer.toHexString(msg[pVal++]).toUpperCase());
         break;
    case 3:
         if (pragma3==true) {
         System.out.println("in switch 3"); ;
         argString = (parameters[1] + parameters[2]);
         msg = x.translate(argString); //*********TRANSLATE()************
         if (pragma3==true) {
         System.out.print("msg translation array = ");
         for (pVal=0; pVal<4;pVal++)
         System.out.print(Integer.toHexString(msg[pVal]).toUpperCase() + ",");
         System.out.println(Integer.toHexString(msg[pVal++]).toUpperCase());
         break;
    default:
         System.out.println("Argument length error");
    break;
    // rc.writeCmd(msg);
    import java.text.*;
    import java.text.StringCharacterIterator; // required for CharacterIterator class
    public class Xlate {
    private String[] commandList; // declares a string variable
    public Xlate() { this(""); }
    public Xlate(String[] msg) { this.commandList = msg[1]; } // holds the name
    public String getCommandStrings() { return this.commandList; } // gets the commandList
    // These methods form a basic translation mechanism used as proof
    public int[] translate(String msg) {
    int[] paramList = {
         0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; //initialise this array
    //Power On and Off controls
    if (msg == "start") {
    paramList = new int[] {
         0xFF, 0xFF, 0xFF, 0x01, 0x20};
    if (msg == "stop") {
    paramList = new int[] {
         0xFF, 0xFF, 0xFF, 0x00, 0x20};
    return (paramList);
    public int[] translate(String msg, int val) {
    int[] paramList = {};
    int pVal;
    // Memory recall with memory ID.
    if (msg == "M") { // Recall memory
    paramList = new int[] {
         0xFF, 0xFF, 0xFF, 0xFF, 0x02};
    // stuff the argument in to the paramList array
    paramList[3] = Integer.decode(Integer.toHexString(val)).shortValue();
    return (paramList);
      public int[] translate(String msg, String aValString) {
    // Convert the string
        int i, j, k;
        int index = 0, c = 0;
        int[] p, paramList = {};
        final StringBuffer result = new StringBuffer(); // only ever one buffer
        char character;
        if (msg == "pause") {
          paramList = new int[] {
           0xFF, 0xFF, 0xFF, 0xFF, 0x0A};
    // The period character is the axle where operations centre...
    // working from the left most position index until period is found.
    // append chars to result string en route.
    // if period then stop - this is the integer part
        StringCharacterIterator sci = new StringCharacterIterator(aValString);
        result.append('0'); // a fudge to pad out the resulting string
        character = sci.current();
        while (character != '.') {
          //char is not a period so append to buffer
          result.append(character);
          character = sci.next();
        character = sci.next();
    // working from the position of 'the period character' append chars to result string en route.
    // stop at the end having bound the fraction part
        while (character != StringCharacterIterator.DONE) {
          result.append(character);
          character = sci.next();
        aValString = result.toString(); // save the result
        sci = new StringCharacterIterator(aValString);
        String[] part = {
         "00", "00", "00", "00"}; // array index ordered 0 to 3 from left to right
        result.delete(0, result.capacity()); // initialise the StringBuffer result
        character = sci.first();
        for (index = 0; index <= 3; ++index) {
          for (i = 0; i <= 1; ++i) {
         if (character != StringCharacterIterator.DONE) {
           result.append(character);
           character = sci.next();
         else {
           result.append('0');
          part[index] = result.toString();
          result.delete(0, result.capacity()); // initialise the StringBuffer result
    // the sequence handles the conversion of decimal to packed BCD for transmission
        for (k = 0; k <= 3; k++) {
          // cast the String in the array part indexed by k to an int
          i = Integer.parseInt(part[k]);
          for (j = 0; j < 10; j++) {
         if ( (i >= (j * 10)) & (i < ( (j + 1) * 10))) {
           paramList[k] = (j * 0x10 + (i - (j * 10)));
        return (paramList);

    Sorry, this is way too much to look at (at least for me). Please create a small test function that fails & post the formatted code. In doing this, you may even spot the problem yourself!

  • Using Accessor Method from Within Considered Best Practice?

    I was wondering what is considered best practice in the AS3 world regarding this topic.
    In C++ and .NET world, as well as PHP I would consider using accessor methods, instead of directly accessing the class property, bad practice due to unnecessary overhead.
    What are your thoughts in this?

    Getters and setters and bindable vars can be public, protected or private.  Which one you choose follows standard object-oriented practices.
    is just like a macro that defines a particular get/set pair.  I would only use it on vars.  Using it on a getter simply wraps the getter in another get/set pair which is wasteful.  The Flex Framework rarely uses .  Instead, we typically define get/set pairs with metadata so we can control what event fires and when.  It also saves SWF size because the compiler doesn't have to generate a long and ugly name to avoid name collisions.
    Alex Harui
    Flex SDK Developer
    Adobe Systems Inc.
    Blog: http://blogs.adobe.com/aharui

  • Why private variables, while still can be accessed by accessor methods

    Agreed it is well defined way of encapsualtion. But i wonder how it works differently. can any one explain . We declare a varibale as private which can be accessed by accessor (set/get) methods which are usually public. so why dont we say vairbkles itself as Private ??
    Pls explain

    Not only that, but imagine the case where you have an api method, getTotal(). Your first iteratation you have something like:
    double gross;
    double net;
    double commission;
    so to get the total you may want gross - commission = net. Thus your method may look like:
    public double getTotal()
    return gross - commission;
    But later on, iteration 2 or so, you find out you need to account for taxes, so now you don't want to break the code, the result should be the same, the NET total. However, you now need to account for taxes:
    public double getTotal()
    return (gross - commission) + tax;
    Without breaking any code and all while maintaining the actual API definition, you have made a public accessor method provide more functionality. All code using the getTotal() method wont break nor has to be recompiled and even better it now takes into account tax.
    Now, there is one "sticky" issue in the above. Because the getTotal() makes direct use of "private" variables, you may not get the "right" tax. In other words, what if there is state and local tax that need to be added? You may have two variables:
    double localTax,stateTax;
    The problem is, do you want your method like this:
    public double getTotal()
    return (gross - commission) + localTax + stateTax;
    Or would it look (and possibly account for future updates) better like so:
    return (gross - commission) + getTax();
    The thing is, what if later on you have additional tax to handle? Sure, you can simply add it to the end, adding it, what ever. But by making a "helper" method of getTax(), you might have on iteration 2:
    private double getTax()
    return localTax + stateTax;
    and in iteration three, you may have:
    private double getTax()
    return localTax + stateTax + salesTax;
    Now, unless you are calling code in an intensive performance needy loop, making a couple of helper method calls won't hurt performance at all, and it will greatly enhance your code quality because you can easily change the implementation of the method(s) used, without affecting the API.

  • Protected vs Private w/ accessor methods

    What is the difference, is there one? Or is it just preference.
    Thank You

    He was pointing out a mistake in your first post. The point of an accessor is to allow access to a private member variable. However, if the accessor method is private just like the field it is supposedly providing access to, then there really is no point!

  • Commenting accessor methods

    Hi,
    In one of my java classes which I have programmed, I put several public getter and setter methods (accessors), and made my fields private. Now I wonder about the documentation commentation.
    What I did is I commented the private fields. But this information is actually necessary for the user of the getter and setter methods. So should I just copy the doc comments of private fields into the doc comments of the getter and setter methods?
    Or is there another way or convention?
    Kind regards,
    Aurote

    kajbj wrote:
    Javadoc the getters and setters. Javadoc is usually not generated for private fields / methods.
    KajI'd say it depends.
    public class Person {
      private String name;
      private Date birthDate;
      private Gender gender;
      public void setName(final String name) {
        this.name = name;
      public String getName() {
        return name;
    // ... etc. ...I would not necessarily javadoc those. For simple get/set that do the obvious, It's just clutter. Maybe for birthDate I would comment whether it makes a copy of the Date, since Date is mutable.

  • Read binary file information from servlet - from database accessor method

    Okay, I have been working on this for awhile now and I just plain dont know what I am doing. Could someone please help me? I cannot find any examples through google or the forums for this specific type of situation( as in a servlet calls a method which gets binary file from a database).
    - How do I get the inputStream into the servlet so that I can read it?
    - Why am I getting the error message that OutputStream has already been called?
    If someone could give me direction or simply tell me what I should look up - I would really really appreciate it.
    The Servlet
    response.setContentType("application/msword");
    response.setHeader("Content-disposition","attachment; filename="+ file + ext);
    OutputStream os = response.getOutputStream();
    OOT openAttachments = searchInfo.openAttachments(newID, oot, ootNum, file, ext, os);
    InputStream is2 = oot.getIs();
        byte b[] = new byte[16384];
        int numBytes;
            while((numBytes=is2.read(b))!=-1){
                os.write(b,0,numBytes);
                System.out.println("is - in while" + is);
            is2.close();
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ootMain.jsp?newID="+newID);
    dispatcher.forward(request, response);
            os.flush();
            os.close();
    The Method
    public OOT openAttachments(String newID, OOT oot, String ootNum, String file,
                               String ext, OutputStream os) {
        this.conn = database.SybaseDAO.grabConnection();
        String query = " edited for space'";
        state = conn.createStatement();
        rs = state.executeQuery(query);
            if(rs.next()){
               InputStream is = rs.getBinaryStream(2);
               oot.setIs(is);
               System.out.println("is - in while" + is);
               is.close();
    Error Messages
    (is - in while - method)    sun.jdbc.odbc.JdbcOdbcInputStream@c02a
    (is2 - after - servlet)      sun.jdbc.odbc.JdbcOdbcInputStream@c02a
    IOException: java.io.IOException: InputStream is no longer valid - the Statement
                                      has been closed, or the cursor has been moved
    Mar 14, 2005 9:53:19 AM org.apache.catalina.core.ApplicationDispatcher invoke
    SEVERE: Servlet.service() for servlet jsp threw exception
    java.lang.IllegalStateException: getOutputStream() has already been called for this responseThanks for your help/time -
    Crystal

    Here is the entire exception:
    Mar 16, 2005 9:32:44 AM org.apache.catalina.core.ApplicationDispatcher invoke
    SEVERE: Servlet.service() for servlet jsp threw exception
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
         at org.apache.catalina.connector.Response.getWriter(Response.java:596)
         at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:161)
         at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:111)
         at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:122)
         at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:115)
         at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:182)
         at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:115)
         at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
         at org.apache.jsp.ootMain_jsp._jspService(org.apache.jsp.ootMain_jsp:596)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:302)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:246)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:682)
         at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:581)
         at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:501)
         at oot.display_files.doGet(display_files.java:63)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:106)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:576)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Thread.java:595)
    Mar 16, 2005 9:32:44 AM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet display_files threw exception
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
         at org.apache.catalina.connector.Response.getWriter(Response.java:596)
         at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:161)
         at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:111)
         at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:122)
         at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:115)
         at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:182)
         at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:115)
         at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
         at org.apache.jsp.ootMain_jsp._jspService(org.apache.jsp.ootMain_jsp:596)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:302)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:246)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:682)
         at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:581)
         at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:501)
         at oot.display_files.doGet(display_files.java:63)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:106)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:576)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Thread.java:595)Line 63 is the include...

  • Accessor vs Mutator methods

    Nowadays I'm studying for SCJP 5.0 and I found a strange definition about Encapsulation .
    When I have seen the "Accessor methods"
    To me, it would be related with the both "setters" and "getters" methods
    But on a mock I found this definition:
    "Accessor methods are used to read data members; mutator methods are used to set data members. The mutator methods can validate the parameter values before the values are used to change the state of the internal data model."
    on the mock this sentence would be strong:
    "Accessors methods are used to prevent fields from being set with invalid data."
    the correct would be:
    "Mutator methods are used to prevent fields from being set with invalid data."
    In order to do the exam, how the Sun call that methods?
    - setters and getter methods?
    - Accessor methods and Mutator methods?
    - or only Accessor methods for the both?
    Message was edited by:
    oalexandrino

    I asked that question because I found the following one on the example of mock:
    A class can not be called "tightly encapsulated" unless which of the following is true?
    a.      All member fields are declared final.
    b.      The class is not anonymous.
    c.      The internal data model can be read and modified only through accessor and mutator methods.
    d.      The class is an inner class.
    e.      None of the above
    I think it would be found in:
    Section 5: OO Concepts
    all right?

Maybe you are looking for

  • SLI - Can I use two different video card versions for SLI?

    Hello, Can I use two different generations of MSI video cards that implement the same GPU for SLI?    The two video cards are: MSI N260GTX-T2D896-OCv2 GeForce GTX 260 896MB <-- What I currently have MSI N260GTX-T2D896-OCv3 GeForce GTX 260 896MB MSI N

  • 15 or 17?

    Hey all I am getting a new MacBook Pro tommorow @ the Apple Store and just to say before I ask money is no issue. Now here my question 15 inch high end or 17 inch MacBook Pro? Now I'm really into photography and the 15 inch has a sd card slot this wo

  • How to retrive rate field in taxinvoice

    hi Guru , i Write following code  but rate field not retrive. select kbetr kwert kschl from konv INTO CORRESPONDING FIELDS OF table it_konv FOR ALL ENTRIES IN  IT_VBRk where KNUMV = IT_VBrK-KNUMV  and kschl = 'ZRPR'. loop at it_konv. endloop. select

  • Datafile drop error

    hi friends, I droped a datafile with following command alter database datafile '/abc/user1.dbf' offline drop; after that i deleted file from oprating system . I shutdown the database and restarted But still it is showing in datadictionary table like

  • Error Invalid field format (screen error) in module pool

    Hi experts i am doing module in whichi had many check boxes on screen and each check box has function code means i want to do some thing else . but as i click the first or any other check box i get a error message INVALID FIELD FORMAT (SCREEN ERROR).