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"));
Similar Messages
-
hello,
how to refresh table display using slis and 'reuse_alv_grid_display method'.
when i'm refreshing table display it performs once again reuse_alv_grid_display.and when i back the previous value appear.how to solve it?
neonare you chaning any value in the gird if so use this..
Pass the user_command form name to the Import parameter
I_CALL_BACK_USERCOMMAND .
and have the Dynamic form implementation..
FORM user_command USING ucomm TYPE sy-ucomm
selfield TYPE slis_selfield.
"The below is important for Editable Grid.
DATA: gd_repid LIKE sy-repid, "Exists
ref_grid TYPE REF TO cl_gui_alv_grid.
IF ref_grid IS INITIAL.
CALL FUNCTION 'GET_GLOBALS_FROM_SLVC_FULLSCR'
IMPORTING
e_grid = ref_grid.
ENDIF.
IF NOT ref_grid IS INITIAL.
CALL METHOD ref_grid->check_changed_data .
ENDIF.
CASE ucomm.
WHEN 'REFRSH'.
ENDCASE.
selfield-refresh = 'X'.
ENDFORM. "user_command -
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,
bmI think that's good approach to go with.
Sai Pullabhotla. -
Help: Using Record and Collection Methods
I have created a record and I have to loop for as many records in the "RECORD". However if I attempt using any of the Collection Methods, I get the following error:
ERROR at line 1:
ORA-06550: line 41, column 14:
PLS-00302: component 'EXISTS' must be declared
ORA-06550: line 41, column 4:
PL/SQL: Statement ignored
ORA-06550: line 47, column 26:
PLS-00302: component 'COUNT' must be declared
ORA-06550: line 47, column 7:
PL/SQL: Statement ignored
Here is the SQL I am trying to execute:
DECLARE
TYPE Emp_Rec is RECORD (
Emp_Id Emp.Emp_no%TYPE
, Name Emp.Ename%TYPE
ERec Emp_Rec;
Cursor C_Emp IS
SELECT
Emp_No, Ename
From Emp;
begin
OPEN C_Emp;
LOOP
FETCH C_Emp INTO Erec;
EXIT WHEN C_Emp%NOTFOUND;
END LOOP;
IF Erec.Exists(1) THEN
dbms_output.Put_line('exists' );
else
dbms_output.Put_line('does not exists');
end if;
CLOSE C_Emp;
FOR I IN 1..ERec.COUNT
LOOP
dbms_Output.Put_Line( 'Row: ' || To_Char(I) || '; Emp: ' || ERec(i).Name) ;
END LOOP;
end;
Can anyone help, please?
Thanking you in advance,You only defined a Record and not a collection, therefore you cannot use .EXISTS
This is how you would use record, collection and exists together
DECLARE
TYPE Emp_Rec is RECORD
(Emp_Id Emp.Empno%TYPE,
EName Emp.Ename%TYPE );
TYPE Emp_tab is table of emp_rec index by binary_integer;
ERec Emp_tab;
Idx INTEGER;
Cursor C_Emp IS
SELECT EmpNo, Ename From Emp;
begin
IDX := 1;
OPEN C_Emp;
LOOP
FETCH C_Emp INTO Erec(IDX);
EXIT WHEN C_Emp%NOTFOUND;
IDX := IDX + 1;
END LOOP;
IF Erec.Exists(1) THEN
dbms_output.Put_line('exists' );
else
dbms_output.Put_line('does not exists');
end if;
CLOSE C_Emp;
FOR I IN 1..ERec.COUNT LOOP
dbms_Output.Put_Line( 'Row: ' || To_Char(I) || '; Emp: ' || ERec(i).eName) ;
END LOOP;
end;I hope you realize that this is only an example of how to use RECORD, COLLECTIONS and Collection Methods (.EXISTS, .COUNT)
and not the best way to display the contents of a table. -
Using serialize and deserialize methods generated by clientgen
I am trying to use the classes generated by the weblogic.webservice.clientgen tool
from the weblogic 8.1 release. I would like to be able to make direct use of
the serialize and
deserialize methods in the "Codec" classes that correspond to the various request
and
response object classes. However, these methods require SerializationContext
and
deserializationContext objects as inputs. Are these context objects things I
can construct,
manufacture and/or access? Are there any coding examples for using these methods?
Thanks.
MichaelBruce,
Thanks for the response. I have seen the documentation before. What that shows
me is how
to write customized Serialize and Deserialize methods. What I want to do is call
the ones that
clientgen has already created for me. I would love to have these called by the
internals of the
generated code as part of the handling of service calls. My problem is that the
web site
that I'm calling for these services uses SSL, and every attempt to use the clientgen-generated
services results in the following exception being raised:
javax.net.ssl.SSLKeyException: FATAL Alert:BAD_CERTIFICATE - A corrupt or unuseable
certificate was received.
Since I am successful in making SOAP calls to this same site -- certificate aren't
an issue
for these SOAP calls -- I thought that what I should try is to make the service
calls myself
using SOAP, but to use the generated Serialize and Deserialize methods
to create the request body and process the response body surrounding the SOAP
call.
However, what I'd really like to do
is figure out the cause of the SSLKeyException, and to make the service calls
the way weblogic
intended them to be made. So if you have any suggestions about what might
be causing the exception, I'd appreciate the help.
BTW. In addition to being able to make SOAP calls myself, I've also had some success
making
web service calls using code generated by Apache AXIS's wsdl2java tool and JWSDP's
wscompile
tool; however, neither of these wsdl processors are replacements for clientgen
because they
both have problems dealing with the complex structures described by wsdl files
for the web
services I'm trying to use.
Bruce Stephens <[email protected]> wrote:
Hi Michael,
The De/SerializationContext are internal/private objects. The example
in the doc (you have probably already seen) is a good starting point:
http://e-docs.bea.com/wls/docs81/webserv/customdata.html#1052981
Regards,
Bruce
BTW, Have you considered using XMLBeans?
http://dev2dev.bea.com/technologies/xmlbeans/index.jsp
Michael Horton wrote:
I am trying to use the classes generated by the weblogic.webservice.clientgentool
from the weblogic 8.1 release. I would like to be able to make directuse of
the serialize and
deserialize methods in the "Codec" classes that correspond to the variousrequest
and
response object classes. However, these methods require SerializationContext
and
deserializationContext objects as inputs. Are these context objectsthings I
can construct,
manufacture and/or access? Are there any coding examples for usingthese methods?
Thanks.
Michael -
Comparing dynamic fields of objects using equals and hashCode methods
To compare the different objects of the same class with their contents like jobTitleId, classificationId, deptId & classificationId was to be done and do some manipulations later using Set and Map. I was able to do that by simply overriding the equals and hashCode methods of Object class and was able to fetch the information (like in the following Map).
Map<LocationData, List<LocationData>>
The following is the class I used (its been shown to you so that it can be referred for my problem statement):
LocationData class
package com.astreait.bulkloader;
public class LocationData {
String locId, deptId, jobTitleId, classificationId;
@Override
public boolean equals(Object obj) {
LocationData ld = (LocationData)obj;
return this.deptId.equals(ld.deptId) && this.jobTitleId.equals(ld.jobTitleId) && this.classificationId.equals(ld.classificationId) &&
this.locId.equals(ld.locId);
@Override
public int hashCode() {
return deptId.hashCode() + jobTitleId.hashCode() + classificationId.hashCode() +locId.hashCode();
Problem:
I'm already known to which all fields of this object I need to make the comparison.
i.e I'm bound to use the variables named classificationId, deptId, jobTitleId & locId etc.
Need:
I need to customize this logic such that the fields Names (classificationId, deptId, jobTitleId & locId etc) can be pulled dynamically along with their values. So, as far as my understanding I made use of 2 classes (TableClass and ColWithData) such that the List of ColWithData is there in TableClass object.
I'm thinking what if I override the same two methods `equals() & hashCode();`
such that the same can be achieved.
TableClass class #1
class TableClass{
List<ColWithData> cwdList;
@Override
public boolean equals(Object obj) {
boolean returnVal = false;
// I need to have the logic to be defined such that
// all of the dynamic fields can be compared
return returnVal;
@Override
public int hashCode() {
int returnVal = 0;
// I need to have the logic to be defined such that
// all of the dynamic fields can be found for their individual hashCodes
return returnVal;
ColWithData class #2
class ColWithData{
String col; // here the jobTitleId, classificationId, deptId, locId or any other more fields info can come.
String data; // The corresponding data or value for each jobTitleId, classificationId, deptId, locId or any other more fields.
Please let me know if I'm proceeding in the right direction or I should make some any other approach. If it is ok to use the current approach then what should be performed in the equals and hashCode methods?
Finally I need to make the map as: (Its not the concern how I will make, but can be considered as my desired result from this logic)
Map<TableClass, List<TableClass>> finalMap;Hello,
What is the relation with the Oracle Forms tool ?
Francois -
Login to a website using httpURLConnection and GET methods
Hello,
I would like to write a java program that connects to a website, logs in by sending relevant data to the javascript I copy-pasted below and then retrieves the information of the webpage reached after successful login.
<FORM method="post" name="loginForm" action="/cvg/dispatch/login/submit">
<TABLE>
<TR>
<TD>
<TABLE BGCOLOR=#D0E2FF WIDTH="100%" BORDER="0" CELLPADDING="3" CELLSPACING="0">
<TR><TD COLSPAN=2>�</TD></TR>
<TR>
<TD ALIGN="RIGHT"><FONT SIZE=3>login</FONT></TD>
<TD><input type="text" name="loginValues.userName" value="" size="15" maxlength="30" ><input type="hidden" name="priority-normal" value="loginValues.userName"></TD>
</TR>
<TR>
<TD ALIGN="RIGHT"><FONT SIZE=3>password</FONT></TD>
<TD><input type="password" name="loginValues.password" value="" size="15" maxlength="30" ><input type="hidden" name="priority-normal" value="loginValues.password">
</TD>
</TR>
<TR>
<TD ALIGN="CENTER" COLSPAN=2>
<input type="image" name="Login" value="Login" src="/cvg/images/login-button.gif" alt="Login" border="0" width="67" height="33" ><input type="hidden" name="submitButton" value="Login"><input type="hidden" name="Login-action" value="Login">
</TD>
</TR>
</TABLE>
Thanks for your helpUsing POST
http://forum.java.sun.com/thread.jspa?threadID=645830
second POST
Using GET
URL u = new URL("http://server/cvg/dispatch/login/submit?loginValues.userName=user&priority-normal=loginValues.userName&loginValues.passwor=password&priority...")
By the way the html you provided does not use GET at all, it uses POST
<FORM method="post" ring any bell?
As for javascript, I don't see any script on the html page you provide, nor
do I see any onsubmit or onclick action. -
Is it possible to use doGet() and doPost method in one jsp
i am having a jsp form which will perform upload as well as download.There is a seperate servlet for download and upload.For downloading i use doGet method and doPost for the upload.how can i change the method dynamically for the above cases.
Hi,
in your jsp, if you call:
request.getMethod();
it should the string "GET" or "POST" depending on the HTTP method used, so you could do something like
<%
String httpMethod = request.getMethod();
if ( "GET".equals(httpMethod) ) {
// code to handle get requests
else if ( "POST".equals(httpMethod) ) {
// code to handle post requests
%>
I probably would of done it in a servlet(override doGet and doPost), or 2 seperate jsps
Hope this helps
Dominic -
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." -
Javascript array ;Add and remove elements without using push and pop
Hi
I need to perform add and remove operation in Javascript with following scenarios
i) Add element, if element does not exist in array(javascript)
ii) Remove element, if element exist in array(javascript)
Without using push and pop method how to achieve this?
Regards
SivaCompleted the Scenario.
-
Why do we need get and set methods?
It is considered good design practice to keep all class data private and
provide get and set methods for accessing the data in a controlled
manner.
So, instead of directly accessing the class data, you use getter and setters.
I do not really feel the need to use get and set methods.
How does that achieve encapsulation when ultimately the class data is being exposed?A couple of reasons why to use get and set:
1. For example you can set an int value for month, if a user sets this to somting
higher than 12 (or 11 if it's zero based) you want to handle that by either
throwing an exception or adding a year for every time it can be devided by 12.
If you dont do it in set you'll have a whole bunch of methods that might need to
correct the value before retreiving the eventual date.
2. If for some reason you have security set up for certain values you can
implement this in the get method. When this is done somewhere else you have
a whole bunch of methods retreiving the info in other classes that need to check
first. (a canGet method could allso be used). Another good reason to use get
is when the information needs to be converted depending on the consumer
calling the get method.
3. If any logic in 1 or 2 changes you'll have a bunch of code to change.
If you feel there is no need to implement any security, error handling (on
compiling because get and set might throw something) or validation when
setting/getting these values there is still the argument of readabillity.
Eclipse has a feature that will generate getters and setters for you so it's not
like there is a lot of extra typing involved.
Got interupted whyle typig so sorry to repeat any answer given before. -
I use Lightroom and iPhoto. I mainly use Lightroom for everything. If it's personal photos I use iPhoto but mostly Lightroom. If I want to share these and/or sync with other devices like AppleTV, iPhone, MobileMe then I have to export from Lightroom to iPhoto. That doubles up on files and hard drive space. What do others do that use Lightroom and iPhoto? I love being able to share and sync with iPhoto but it's just to much to ask of my Hard Drives.
Few people use both Lightroom and iPhoto - they both do essentially the same thing but are different and in the past iPhoto has found LR processed photos unacceptable - and they can not operate on the same physical photos - you must export photos form LR and import them into iPhoto since they both manage photos
If you want to use both you will have to have photos imported into each
Fortunately external hard drives are cheap -- iPhoto is perfectly happy having its library on an EHD
LN -
MsSaveBlob and msSaveOrOpenBlob methods on IE 10
I am facing issues in using the msSaveBlob and msSaveOrOpenBlob methods on IE 10. These methods seem to be working on IE 11 and IE 10 version 10.0.9200.17183 but the API fails on IE 10 version 10.0.9200.16844.
I am trying the Example 1 code on this site http://msdn.microsoft.com/en-us/library/ie/hh779016%28v=vs.85%29.aspx#blobbuilder
Is there an alternate method to export blob on the version of IE 10 where the methods are failing?Do you get any error message when you fail to use msSaveBlob and msSaveOrOpenBlob methods on IE 10?
So have you tried the others two ways to manage local files?
Saving files locally using Web Storage
Saving files locally using IndexedDB
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Choice between xquery and parsing methods
I want to read from an xml source file. I have been working with parse techniques (JAXP )and Marshal/Unmarshal techniques(JAXB).
Recently i came to know that we can query an xml document using xquery and
xpath methods.
Is the second method advantageous than the first one in terms of time and memory constraints ?Yes, xquery and xpath are always easy to work than parsing on your own.
It provides already written methods for u, which u need not to write on your own to fetch the data.
Hope this will help u.
......yogesh -
Revision: 13042
Revision: 13042
Author: [email protected]
Date: 2009-12-17 03:45:27 -0800 (Thu, 17 Dec 2009)
Log Message:
Fix for FM-287, reinstating the main sample (that uses serial and parallel composition), and making another pass at getting all the changed trait methods mapped correctly back- and forth between JS and Flash.
Ticket Links:
http://bugs.adobe.com/jira/browse/FM-287
Modified Paths:
osmf/trunk/apps/samples/framework/HTMLGatewaySample/HTMLGatewaySample.as
osmf/trunk/apps/samples/framework/HTMLGatewaySample/html-template/index.template.html
osmf/trunk/framework/MediaFramework/org/osmf/external/HTMLElement.as
osmf/trunk/framework/MediaFramework/org/osmf/gateways/HTMLGateway.asPerre wrote:I'm used to being able to pick one or a couple of songs and then adding it a specified playlist. Is this impossible in sonata?
It's clearly not impossible, just different than you expect. Create your playlist as you want it to appear in the Current tab (meaning don't dump every single song from your library in there, just the ones you want) and then save the playlist.
Perre wrote:And if I try to play the m3u file created (the one with every song listed) through freevo I get a message that the directory is empty. What am I doing wrong??
Look at save_absolute_paths_in_playlists in your mpd.conf.
Maybe you are looking for
-
I waited too long to get around to buying one and now newegg and zipzoomfly are both out of stock... They are few and far between on ebay... are they being discontinued? Hopefully there are still some out there (pref. under $300)...
-
Dynamically changing Universe Connection
We are in the process of implementing CM (Configuration Management) process to migrate the code from Development to QA to Production. Currently we are taking the code from Development using Import Wizard and creating a BIAR file, move that BIAR file
-
Data Loading into BW ( from excel to database table)
Hi Guys I have an excel sheet which has the fields: --> Soldto(3.1), Soldto(4.6), Shipto, Billto, Payer, SalesOrg, AAG. I also have a database table /BIC/AZSTXREF00 in BW QA (SE16), which has fields: --> /BIC/ZSOLD_TO(3.1), /BIC/ZBTOPRTY, PAYER, SHIP
-
'Select WLAN Network' every time I boot! Grr.
I can't wait to get rid of my Nokia E71 - the most infuriating, badly designed, buggy piece of technology ever 'created' (more like shoved into existence). In the meantime I am stuck with it on contract, and have one (well 15) particularly annoying
-
Reversing fee calculation document
Dear all, I created a document in fee calculation. How can I reverse it? Thanks