The Artima Developer Community
Sponsored Link

Java Answers Forum
Quick BufferedWriter question

1 reply on 1 page. Most recent reply: Jul 11, 2003 10:24 AM by Erik Price

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Chris Brooks

Posts: 6
Nickname: bioheel
Registered: Jul, 2003

Quick BufferedWriter question Posted: Jul 10, 2003 12:31 PM
Reply to this message Reply
Advertisement
I have two objects: Reader and Distance. I have created a BufferedWriter in the Reader class and write in the Distance class. The reason if that I don't want to overwrite previously written data as I go through the for loops. When I run the compiler on Distance I get a "variable might not have been initialized" error on dist.write -- any help would be appreciated.

Relevant code from Distance:

public void appendFile() {

try {
FileWriter fiw;
BufferedWriter dist;
String sA = Integer.toString (A);
String sB = Integer.toString (B);
String sd = Double.toString (distance);
String newData = new String(sA+sB+sd);
dist.write(newData);
}
catch (Exception e) {
System.out.println("Program Error - Aborting");
}
}


Erik Price

Posts: 39
Nickname: erikprice
Registered: Mar, 2003

Re: Quick BufferedWriter question Posted: Jul 11, 2003 10:24 AM
Reply to this message Reply
The problem is that although you have declared a BufferedWriter reference variable named dist, you haven't actually assigned it to any objects. Therefore it has no value, and when the compiler sees dist.write(), it doesn't understand what object it should invoke write() on.

You must assign the dist reference variable a value. You have three choices:

1) Use a constructor: BufferedWriter dist = new BufferedWriter();
2) Use the return value of a method: BufferedWriter dist = someOtherObject.getWriter();
3) Assign null: BufferedWriter dist = null;

You probably want Option 1. If you choose option 2, you will need to have another object with a method that returns a BufferedWriter or a subtype of BufferedWriter. If you choose option 3, your code will compile but will throw a NullPointerException at runtime.

Flat View: This topic has 1 reply on 1 page
Topic: Simple method - requires urgent help! Previous Topic   Next Topic Topic: My First Applet Help

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use