-1

I have a java assignment, and my last two errors are laid out in this code. For a little background, my code is taking input from a GUI and writing it into a text file. I realize you may need more code, and I will give more if needed, I just can't seem to understand these errors. Here is my code:

public void dataWriter(String data, String fileName) throws IOException 
{
File file = getFileStreamPath(fileName);

if (!file.exists()) 
{
   file.createNewFile();
}

    try (FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE)) // Error "cannot find symbol, variable MODE_PRIVATE"
    {
        for (String string = null, data)//error "variable data is already defined in dataWriter"
        {
            {
            writer.write(string.getBytes());
            writer.flush();
            }   
        }
    }
    catch (Exception e)
    {

    }

}

Any help is greatly appreciated. Thank you so much!

Paul
  • 49
  • 2
  • 11

1 Answers1

0

From the original question it looks as though you are trying to write out to a file. OK, something like this should work:

public void dataWriter(String data, String fileName) throws IOException {

PrintWriter writer = new PrintWriter(new FileOutputStream(new File(fileName));

try {
  writer.write(data);
} catch (Exception e) {
  System.err.println("Some exception");
} finally {
   writer.close();
}

The issue you were having with your above code was that the for loop syntax in Java is very different than how you originally stated.

Instead of for (String string = null, data)

An iterative for loop needs to look like this:

for (int i = 0; i < someDataStructure.size(); i++)
    someDataStructure.get(i);

You could also do a for each loop if the Data Structure implements Iterable.

However, all this aside, you were attempting to iterate using a FileOutputStream when you had no List or Array over which to iterate, had you passed in another reference to a file or a list, the iteration should have looked something like this:

public void dataWriter(List data, String fileName) throws IOException {

PrintWriter writer = new PrintWriter(new FileOutputStream(new File(fileName));

try {

  for (int i = 0; i < data.size(); i++) 
      writer.write(data);

} catch (Exception e) {
  System.err.println("Some exception");
} finally {
   writer.close();
}
andrewdleach
  • 2,458
  • 2
  • 17
  • 25
  • I disagree with the decision to post a complete answer to a homework question on principle. Did he learn anything? He was having a problem understanding basic for-loop syntax... – jgitter Aug 13 '15 at 17:47
  • @jglitter ok, i'll add commentary to it, for a better description. – andrewdleach Aug 13 '15 at 17:48