Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2006

Tip: Looking for answers? Try searching our database.

Static methods

Thread view: 
Woot4Moo@gmail.com - 26 Dec 2006 19:56 GMT
Hi guys I am working on a program and I cant seem to figure out where
it is I am going wrong.
It is involving Bank accounts and PINs.  I have a Bank class and a
BankAccount class.

In my BankAccount class I have a variable declared as private static
int pin.
as well as:
public static int checkPin()
{
 return pin;
}

In my Bank class I have
public double getBalance(String nameOfOwner, int finalPin)
{
int pin = BankAccount.checkPin();
if(pin != finalPin) return -1;
// rest of code to get balance, which works properly.
}

My question is how do I make it so the pin can be referenced for each
account and also so that pin does NOT get over written everytime a new
account is created.  Because currently what happens is the pin is only
stored for the last account created.

Thanks
Joe Attardi - 26 Dec 2006 20:03 GMT
On Dec 26, 2:56 pm, Woot4...@gmail.com wrote:
> In my BankAccount class I have a variable declared as private static
> int pin.
[quoted text clipped - 3 lines]
> account is created.  Because currently what happens is the pin is only
> stored for the last account created.

A static variable has the same value for every instance of the class.
So you are basically assigning the same PIN to every account. You want
this to be an instance variable, i.e.

private int pin;

public int getPin() {
  return pin;
}

This will allow each instance to have its own PIN, which is what you
want.
Flo 'Irian' Schaetz - 26 Dec 2006 20:04 GMT
And thus spoke Woot4Moo@gmail.com...

> In my BankAccount class I have a variable declared as private static
> int pin.
[quoted text clipped - 3 lines]
>   return pin;
> }

This means, that only ONE Pin does exist, no matter how many accounts
you create. Every account will access THIS ONE Pin. Are you really sure
that you want to do that?

> My question is how do I make it so the pin can be referenced for each
> account and also so that pin does NOT get over written everytime a new
> account is created.  Because currently what happens is the pin is only
> stored for the last account created.

That's because the variable Pin exists only ONE time. It does NOT exist
one time for each account. Static means exactly that: Not every account
has it's own pin, there is only one "global" pin instead.

So if you want every account to have it's own pin, remove the static.
And please read some good tutorials about Java. :-)

Flo
jupiter - 26 Dec 2006 21:48 GMT
> And thus spoke Woot4Moo@gmail.com...
>
[quoted text clipped - 12 lines]
> really sure
> that you want to do that?

What's the matter with that?  There's only one customer at his
lousy bank.
Stefan Ram - 26 Dec 2006 22:38 GMT
>>>In my BankAccount class I have a variable declared as private
>>>static
>>>int pin.
>What's the matter with that?  There's only one customer at his
>lousy bank.

 /* Why? Here is a class with a static field: */

public class Scan { static int i = 0; public static int get(){ return i++; }}

 /* Let's create two instances of it: */

public class Main
{ public static void main( java.lang.String[] args ) throws java.lang.Exception
 { final java.lang.Class instance1 = new ScanLoader().loadClass( "Scan" );
   final java.lang.Class instance2 = new ScanLoader().loadClass( "Scan" );
   final java.lang.Class[] c = new java.lang.Class[]{};
   final java.lang.Object[] o = new java.lang.Object[]{};
   java.lang.System.out.println( instance1.getMethod( "get", c ).invoke( null, o ));
   java.lang.System.out.println( instance1.getMethod( "get", c ).invoke( null, o ));
   java.lang.System.out.println( instance2.getMethod( "get", c ).invoke( null, o ));
   java.lang.System.out.println( instance2.getMethod( "get", c ).invoke( null, o )); }}

 /* There are really two different static fields, as they can
    count independently:

0
1
0
1

    The rest of the code: */

class ScanLoader extends ClassLoader
{ public ScanLoader()
 { super(ScanLoader.class.getClassLoader()); }
 public java.lang.Class<?> loadClass( final java.lang.String className)
 throws ClassNotFoundException
 { return findClass( className ); }
 public java.lang.Class<?> findClass( final java.lang.String className )
 { byte classByte[];
   java.lang.Class<?> result = null;
   if( "java.lang.Object".equals( className ))return java.lang.Object.class;
   try
   { java.lang.String classPath =
     ((java.lang.String)ClassLoader.getSystemResource
     ( className.replace( '.', java.io.File.separatorChar ) + ".class" ).getFile() ).
     substring( 1 );
     classByte = loadClassData(classPath);
     result = defineClass(className,classByte,0,classByte.length,null);
     return result; }
   catch(final java.lang.Exception e){ throw new java.lang.RuntimeException(e); }}
 private byte[] loadClassData
 ( final java.lang.String className )
 throws java.io.IOException
 { final java.io.File f = new java.io.File( className );
   final int size =( int )f.length();
   final byte buff[] = new byte[ size ];
   { java.io.FileInputStream fis = new java.io.FileInputStream( f );
     { java.io.DataInputStream dis = new java.io.DataInputStream( fis );
       dis.readFully( buff );
       dis.close(); }}
   return buff; }}
jupiter - 27 Dec 2006 04:19 GMT
>>>>In my BankAccount class I have a variable declared as private
>>>>static
[quoted text clipped - 3 lines]
>
>  /* Why? Here is a class with a static field: */

Sorry, I was only making a joke (about the bank only having one
customer), Stephan.

Nevertheless, you provided a nice example.  Thanks, I've never
stepped through it like that.

> public class Scan { static int i = 0; public static int get(){
> return i++; }}
[quoted text clipped - 67 lines]
>        dis.close(); }}
>    return buff; }}
Eric Sosman - 26 Dec 2006 20:07 GMT
> Hi guys I am working on a program and I cant seem to figure out where
> it is I am going wrong.
[quoted text clipped - 21 lines]
> account is created.  Because currently what happens is the pin is only
> stored for the last account created.

    Get rid of `static' (in both places).  A `static' variable
belongs to the class as a whole, rather than to any particular
instance of the class.  No matter how many BankAccount objects
you create, there will be only one `static int pin' and it will
hold only one value at a time.  Without `static', each BankAccount
will have its own pin variable, and the pin values of two different
BankAccount objects can be different.

Signature

Eric Sosman
esosman@acm-dot-org.invalid

Woot4Moo@gmail.com - 26 Dec 2006 20:13 GMT
Originally that is what I had but when I tried to check the PIN in my
Bank class it was giving me problems about it being non-static.   So
that is why I had changed it originally.
Eric Sosman - 26 Dec 2006 20:34 GMT
> Originally that is what I had but when I tried to check the PIN in my
> Bank class it was giving me problems about it being non-static.   So
> that is why I had changed it originally.

    (Please quote enough context to make your message
understandable on its own.)

    For those who haven't seen what's gone before, Woot4Moo
has a BankAccount class that contains a `private static int pin'
variable and a `static int checkPin()' method.  He's wondering
why all BankAccounts have the same pin value, and he's been
advised (by me and others) to get rid of `static'.

    Back to the action: Woot4Moo, I suggested that you get
rid of `static' "in both places," meaning both on the declaration
of the pin variable and on the checkPin() method.  From your
vague description of the problem, I suspect you have eliminated
only one occurrence of `static'.

    If you have eliminated both and are still having trouble,
please post a *complete* self-contained example of the code
and the *exact* text of any error messages you receive.  We're
not mind readers.

Signature

Eric Sosman
esosman@acm-dot-org.invalid

Flo 'Irian' Schaetz - 26 Dec 2006 21:14 GMT
And thus spoke Woot4Moo@gmail.com...

> Originally that is what I had but when I tried to check the PIN in my
> Bank class it was giving me problems about it being non-static.   So
> that is why I had changed it originally.

public double getBalance(String nameOfOwner, int finalPin)
{
int pin = BankAccount.checkPin();

THIS won't work, of course, if you make the pin non-static (as it should
be). You will need something like...

public double getBalance(Account account, int finalPin)

...or...

public double getBalance(String nameOfOwner, int finalPin)
{
BankAccount account = ... // Somehow get the account of the owner
int pin = account.checkPin();

Oh, and btw: As your method "checkPin" doesn't really "check" the pin,
justs gets it, I would call it "getPin" instead. checkPin would be more
something like...

boolean checkPin(int accountPin, int givenPin) {
if (accountPin == givenPin) {
 return true;
}
return false;
}

Flo
Woot4Moo@gmail.com - 26 Dec 2006 22:38 GMT
Woot4...@gmail.com wrote:
> Hi guys I am working on a program and I cant seem to figure out where
> it is I am going wrong.
[quoted text clipped - 23 lines]
>
> Thanks

And now
public class BankAccount
{
 private final String nameOfOwner;
 private double balance;
 private int pin;
}
public BankAccount( String nameOfOwner)
{
  this(nameOfOwner,0,0) ;
}
public BankAccount(String nameOfOwner, double  balance,  int pin)
{
 if(balance < 0 )
  throw  new IllegalArgumentException("Balance must not be negative.
");
 this.nameOfOwner = nameOfOwner;
 this.balance = balance;
 this.pin = pin;
}

public String getNameOfOwner()
{
 return nameOfOwner;
}

public double getBalance()
{
 return balance;
}

private String secureToString()
{
 return "Balance : $ "+  balance + "Name  of owner : " + nameOfOwner;
}

public int checkPin()
{
 return pin;
}
}

public class Bank
{
 private ArrayList(BankAccount) accounts;
}

public Bank()
{
 accounts = new ArrayList(BankAccount)();
}

public boolean addAccount(String nameOfOwner, double  initialBalance,
int pin)
{
  if( initialBalance < 0 ) return false;
  int index = getAccountIndex(nameOfOwner);
  if( index != -1) return false;
  accounts.add( new BankAccount( nameOfOwner,initialBalance, pin ));
  return true;
}

public double getBalance(String nameOfOwner,  int finalPin)
{
  int pin = BankAccount.checkPin();
  if(pin !=  finalPin) return -1;
  int index = getAccountIndex(nameOfOwner);
  if( index  == -1) return -1;
  double finalBalance = accounts.get(index).getBalance();
  return finalBalance;
}

private int mostRecentIndex =  -1;

public int getAccountIndex(String nameOfOwner)
{
 if( ( 0 <= mostRecentIndex &&  mostRecentIndex < accounts.size() )
  &&  nameOfOwner.equalsIgnoreCase(
      accounts.get(mostRecentIndex).getNameOfOwner() ) )
   return mostRecentIndex;
 for(  int i =  0; i < accounts.size(); i++)
{
 if( nameOfOwner.equalsIgnoreCase(
      accounts.get(i).getNameOfOwner() ) )
  {
     mostRecentIndex = i;
     return i;
   }
    return -1;
}
}

There ya go guys and the error I get is
non-static method getPin() cannot be referenced from a static context

int pin = BankAccount.checkPin();
                               ^
Eric Sosman - 26 Dec 2006 23:32 GMT
> Woot4...@gmail.com wrote:
>> Hi guys I am working on a program and I cant seem to figure out where
[quoted text clipped - 32 lines]
>   private int pin;
> }

    ... and right there at the closing } is where the BankAccount
class ends.  Nothing else you've provided is part of BankAccount
(in fact, it's just a bunch of syntax errors caused by placing
must-be-inside-a-class things outside of a class).

    Woot4Moo, if you want help debugging some code you must
provide the *actual* *code* and not some half-hearted rough-
and-ready close-enough-for-jazz paraphrase.  When you visit the
doctor because you broke your right arm, do you present your
left foot for his examination?

    Oh, well -- I have a pretty good idea what's wrong, despite
all your attempts to obfuscate the matter, and in the interests
of Just Getting It Over With ...

> non-static method getPin() cannot be referenced from a static context
>
> int pin = BankAccount.checkPin();

    On various people's advice you've made pin non-static, so
each BankAccount instance can have its own value.  And you've
made checkPin() non-static so it can work on "this" BankAccount
instance instead of working on the BankAccount class.  Fine.

    But: Which BankAccount instance owns the pin that you are
trying to check?  If you walk into a large bank and ask "Is
this PIN valid?" the likely answer is "Probably."  (The bank
has 100000 accounts and there are only 10000 possible PIN
values, so chances are pretty good that any PIN you choose is
valid for *some* account.)

    Instead, you need to ask "Is this PIN valid for account
number such-and-such?"  You must ask the question in relation
to some particular BankAccount, not in relation to the "schema"
from which all BankAccounts are created.  So: You start with
the name of the account owner, from that you must find the
BankAccount he owns, and *then* you can ask *of that BankAccount*
whether the pin is correct.

Signature

Eric Sosman
esosman@acm-dot-org.invalid

Woot4Moo@gmail.com - 26 Dec 2006 23:48 GMT
Most  appreciated even though I did think that those were 2 seperate
classes my eyes must really be going.
Chris Smith - 27 Dec 2006 04:12 GMT
> Most  appreciated even though I did think that those were 2 seperate
> classes my eyes must really be going.

I'm not trying to drag this out unnecessarily, but copy and paste is a
great thing.  It means that even if you don't notice something about
your own code, you'll still manage to post the right code in your
newsgroup message, so that someone else can spot it for you.  (It's also
a heck of a lot easier than retyping everything all the time!)

Signature

Chris Smith

John Ersatznom - 27 Dec 2006 00:06 GMT
[snip]

I find it interesting that nobody has commented on:
a) The suspicious resemblance to a homework assignment (I haven't had a
comp sci class that *didn't* involve a "Bank and BankAccount" example or
exercise, unless it didn't involve *either* a) OO programming or b) DMBS
*at all*.)
b) The use of "double" to store dollar amounts. Rather than e.g. int
balanceInCents; and methods like getDollars, getChange,
getTotalBalanceInCents ... do you *really* want to sock $499.99 in the
bank and withdraw $499.98999909125? :)
Woot4Moo@gmail.com - 27 Dec 2006 00:12 GMT
> [snip]
>
[quoted text clipped - 7 lines]
> getTotalBalanceInCents ... do you *really* want to sock $499.99 in the
> bank and withdraw $499.98999909125? :)

Well  John  Ill give that much to  you, quite close in saying that its
a hw assignment it was something given to finish out the semester which
ended 2 weeks ago.   Grades are in and such Im just trying to wrap  my
mind around it at this point before I have a second semester of java.
I really am just quite stumped  on this, I failed this program,
obviously.  So all in all I cant really have it change my grade, but I
would  like to have the concept under my belt.
Patricia Shanahan - 27 Dec 2006 17:38 GMT
>> [snip]
>>
[quoted text clipped - 15 lines]
> obviously.  So all in all I cant really have it change my grade, but I
> would  like to have the concept under my belt.

You seem to have grasped the most important point, that learning to
program is a cumulative process, and you will need to understand the
first semester material in order to understand what follows.

Perhaps you should try applying the advice so far, and post you new best
effort, working or not. Do copy-paste, without retyping, so that we get
to see exactly what you are doing.

The newsgroup, collectively, has a lot of experience at working out what
concepts, if any, someone is missing from their code attempts.

Patricia
Woot4Moo@gmail.com - 27 Dec 2006 20:12 GMT
> >> [snip]
> >>
[quoted text clipped - 28 lines]
>
> Patricia

Well it really does come down to  me trying to reference a method from
my BankAccount class into my Bank class, the getPin().   I honestly
cant seem to figure out how to get around the whole static issue.
Maybe I am overanalyzing or perhaps even underanalyzing my situation.
Then again maybe I am just so far lost I should take some time  away
from this and come back to it after a day or so of not thinking about
it.  I do appreciate all the help though.
Matt Humphrey - 27 Dec 2006 17:09 GMT
> [snip]
>
[quoted text clipped - 3 lines]
> exercise, unless it didn't involve *either* a) OO programming or b) DMBS
> *at all*.)

I'm sure everyone here recognized this as homework, but sidestepped the
issue because the OP politely asked for help on a specific question, not for
people to do his homework for him. Homework is not verboten, but must be
asked and answered more carefully. (Guidelines are available on the web.)

> b) The use of "double" to store dollar amounts. Rather than e.g. int
> balanceInCents; and methods like getDollars, getChange,
> getTotalBalanceInCents ... do you *really* want to sock $499.99 in the
> bank and withdraw $499.98999909125? :)

Someone must make the comment first--I guess it's you.

Matt Humphrey matth@ivizNOSPAM.com http://www.iviz.com/
Juha Laiho - 27 Dec 2006 16:07 GMT
Woot4Moo@gmail.com said:
>Hi guys I am working on a program and I cant seem to figure out where
>it is I am going wrong.
[quoted text clipped - 16 lines]
>// rest of code to get balance, which works properly.
>}

You already have gotten advise on some other aspects, but I'd like to
comment on your naming of things.

When you look at the "checkPin" method, does it really check a given pin?
No; what it does is that it gets the pin. Actually you check the pin in your
Bank.getBalance method (the "pin != finalPin" expression).

Rather, you could change the method to really check a pin, by changing
the return value into boolean - like
public boolean checkPin(int pinInput)
{
 return (pin == pinInput);
}

... which you would then use like

public double getBalance(String nameOfOwner, int finalPin)
{
BankAccount account;
// somehow fetch the account for the owner, then check the pin
if(account.checkPin(finalPin)) return -1;
// rest of code to get balance, which works properly.
}

Of course, to continue with this trend, I'm not certain whether
checking the pin belongs into a method called getBalance.
Signature

Wolf  a.k.a.  Juha Laiho     Espoo, Finland
(GC 3.0) GIT d- s+: a C++ ULSH++++$ P++@ L+++ E- W+$@ N++ !K w !O !M V
        PS(+) PE Y+ PGP(+) t- 5 !X R !tv b+ !DI D G e+ h---- r+++ y++++
"...cancel my subscription to the resurrection!" (Jim Morrison)



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.