Jump to content

recognizing same object with both classes

- - - - -

  • Please log in to reply
14 replies to this topic

#1
tier

tier

    Learning Programmer

  • Members
  • PipPipPip
  • 36 posts
I have asome classes, and I want to have only 1 object from some classes (without having to redefine it and get a NullPointerException..).

For example - I defined :

              FileWriter fstream = new FileWriter("log.txt"); 

              BufferedWriter out = new BufferedWriter(fstream);

in class "A", and in it I have:

    public void record(String payed, String guess, String date, boolean won, String result, String sigma) throws IOException{

    

          String message = date +"  payed: "+payed +"$ that $ will be: "+guess +" rsult was: "+result +" total winnings: "+ sigma+"$";

          out.write(message+"\n");

...

but the actual class that updates "A" (uses record) is "B" (which should. obviously contain "A"'s object).

 db.record(f.getBet(), Double.toString((double)f.getSldDlr()/1000), f.getDlu(), won, f.getResultR(),  this.editNum(Double.toString(sum)) ); 

I've tried defining "out" as static, defining it in main, and passing it in "B"'s C'tor, and neither of these helped.

What is wrong here?

Thanks.

#2
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
I'm having a very difficult time understanding what you're trying to do based on your description alone. Could you please post more of your code (such as your class definitions for "A" and "B") and try to restate your problem in a more thorough way?

Edit: Also, please describe the precise nature of your problem. (i.e., won't compile, runtime exception...) Please include the text of any error messages you're getting.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#3
tier

tier

    Learning Programmer

  • Members
  • PipPipPip
  • 36 posts
I'll try...

I get no errors. The problem is that I can't seem to write to the text file (but NetBeans does create it).

My two classes are :


package stockmarket;


import java.io.*;


public class DB {

    

    //static Formatter log;   

     private BufferedWriter out;


      public DB() throws FileNotFoundException {

          try {

              // Create file 

              FileWriter fstream = new FileWriter("log.txt"); 

              out = new BufferedWriter(fstream);


          } catch (Exception e) {//Catch exception if any

              System.err.println("Error: " + e.getMessage());

          }

      }


    public void record(String payed, String guess, String date, boolean won, String result, String sigma) throws IOException{

    

          String message = date +"  payed: "+payed +"$ that $ will be: "+guess +" rsult was: "+result +" total winnings: "+ sigma+"$";

          //System.out.println(message);

          out.write(message+"\n");

          //log.format("%s\n", won ? message + "   -  V" : message + "   -  X");

    }

    

    @Override

    protected void finalize() throws Throwable {

        try {

            out.close();

            // log.close();        // close opened file

        } 

        finally {

            super.finalize();

        }

}

    

}






-----------
-----------



package stockmarket;


import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Random;


public class betting {

    

.

.

. 

    private DB db = new DB();


    public betting(form f) throws FileNotFoundException{

        sum = 0.00;

        this.f = f;      

    }


.

.

.

    // handles win \ lose - setting icons + summing sigma 

    public void afterBet() throws IOException {


        if (f.getBtnState() && (f.getRadDlrState() || f.getRadEroState()) )        //     if button's pushed

        {

                if (won) {

                    f.setPIcRsl("C:\\Documents and Settings\\yoyo\\Desktop\\icons\\16x16-free-application-icons\\png\\16x16\\"

                            + "Thumbs up.png");


                    sum += Double.parseDouble(f.getResult().replace("$", "")) ;

                    f.setResultR("+" + f.getResult());          

                }


                else {

                    f.setPIcRsl("C:\\Documents and Settings\\yoyo\\Desktop\\icons\\16x16-free-application-icons\\png\\16x16\\"

                        + "Thumbs down.png");


                    sum += Double.parseDouble("-" + f.getBet().replace("$", "")) ;

                    f.setResultR("-" + f.getBet());

                }

                

               f.setFldSigma(sum);

               f.setBtnState(false);

               db.record(f.getBet(), Double.toString((double)f.getSldDlr()/1000), f.getDlu(), won, f.getResultR(),  this.editNum(Double.toString(sum)) );     ///////////  records in data DB    * $$$ only

        }       

                

}


.

.

.



So db.record() doesn't really record anything - just creates the text file..
Any design / logic comments are also appriciated...

Thanks

#4
Norm

Norm

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 327 posts

Quote

//System.out.println(message);
Did this message print out (when it wasn't commented out)?

Is the file closed when you are done writing to it?
Add another println statement next to the close() to see.

#5
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
You need to close the stream as well.

finalize() is NOT guaranteed to run.

Try adding out.flush() as last line in the record(..) method. (This makes sure the content is actually written to the file and not kept in the buffer, as I assume the file is never closed properly)

#6
tier

tier

    Learning Programmer

  • Members
  • PipPipPip
  • 36 posts
Thanks.
The file indeed wasn't closed properly.
Now I wonder:

1. What are the differences between Formatter and BufferedReader, and when is it better ?
2. Why won't the text file feed the "\n" of my string, and in genral, how do I have access to the file's writing pointer?
3. If finalize() is not guaranteed to run, how do I make it run \ notify that I want to use it (in cases of closing streams, and not relating on GC, for example)

Thanks

#7
Norm

Norm

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 327 posts

Quote

Why won't the text file feed the "\n" of my string
Can you explain what you want here? What does "feed" mean?

Quote

how do I have access to the file's writing pointer
What is a "writing pointer"?

#8
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Formatter is to format stuff, reader reads.. I don't see how you can compare the 2.

Quote

Why won't the text file feed the "\n" of my string, and in genral, how do I have access to the file's writing pointer?
The \n is actually in the file. But windows won't show it as a newline without it being accompanied with a carriage return, so to display a newline you have to write \r\n

Quote

Norm said:



What is a "writing pointer"?

Quote

If finalize() is not guaranteed to run, how do I make it run \ notify that I want to use it (in cases of closing streams, and not relating on GC, for example)
Just create a method, and call the method yourself. As programmer you should be able to know at what point the file can be closed.

#9
Norm

Norm

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 327 posts

Quote

windows won't show it as a newline without it being accompanied with a carriage return,
There is a difference between wordpad and notepad.

#10
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Noone uses wordpad :P

I don't think \n would've been a problem for notepad++ tho (which I believe every programmer should have installed)

#11
Norm

Norm

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 327 posts

Quote

No one uses wordpad
i'll have to remember that. It seems to work fine for me.

#12
tier

tier

    Learning Programmer

  • Members
  • PipPipPip
  • 36 posts
clarifications:

1 - "Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A)." WIKI

2 - As more of a C++ programer, I'm used to have reference pointers to follow a stream (get and set). I'm aware that Java doesn't specify pointers, but still wondering if there is a way to get that info as well.

3 - I'm asking about the differences and uses of "FileWriter" and "Formatter" as files outputers . I may have been taught / got it ( here - Java Programming Tutorial - 80 - Writing to Files - YouTube , when I searched for "writing to files in java") not correctly.

I'm aware I may ask noob questions.Patience, please.. :)

---------- Post added at 04:12 PM ---------- Previous post was at 03:38 PM ----------

BTW - I implemented a clock which updates a label every second. Was it wisely designed ?
I get warnings from NetBeans for using run() & using a loop within the thread.




public class Timer  implements Runnable{


.

.

.

    // starts the timer + betting iterations

    public void run() {

        

        for (int i = sec; i >= 0; i--) {

            try {

                Thread.sleep(1000);

                f.setLblTime(Integer.toString(i)); 

                

            } catch (InterruptedException ex) {

                Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, ex);

            }

        }

.

.        

.

.

.


        Thread.currentThread().run();

        

    }


}







1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users