954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Need help Using "get and set methods"

I'm using the Scanner class and need help in setting up get and set methods for where the program asks the user to enter a first name and a last name as String type.( 2 methods, 1 for first, 1 for last) I need to know how to store the names because...

I am creating a client of the first class and need to call the methods in order to display what the user inputted at the end of the program.

How do you type code for this?

Any help is appreciated.

Maria5683
Newbie Poster
7 posts since Nov 2004
Reputation Points: 10
Solved Threads: 0
 

First, do you really need set methods? Most of the time you can use constructor arguments to set the fields and set methods aren't required:

Scanner in = new Scanner ( System.in ).useDelimiter ( ' ' );

System.out.print ( "Full name (ex. John Smith): " );
String first = in.next();
String last = in.next();

Client obj = new Client ( first, last );

Then writing the get methods only consists of returning the necessary field. The chances of an object representing a person needing to change the name are very slim, so set methods don't make much sense except in very specific situations.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

class MyDate
{
int dd,mm,yy;
public void initDate ()
{
dd=mm=yy=0;
}
public void setDate(int d,int m,int y)
{
dd=d;
mm=m;
yy=y;
}
public void dispDate()
{
System.out.println(

saurabh.agrawal
Newbie Poster
2 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

class MyDate
{
int dd,mm,yy;
public void initDate ()
{
dd=mm=yy=0;
}
public void setDate(int d,it m,int y)
{
dd=d;
mm=m;
yy=y;
}
public void dispDate()
{
System.out.println("Date is:"+dd+"-"+mm+"-"+yy);
}
public static vo main (String args[])
{
MyDate D1;
d1=new MyDate();
d1.initDate();
d1.dispDate();
d1.setDate(3,7,90);
d1.dispDate();
}
}

saurabh.agrawal
Newbie Poster
2 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

Please use code tags when posting your code. use the rightmost icon above the text input field. The one that says: [CODE]

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You