-2

I want to create a method that which opens a file for writing, then prompts the user to enter lines of text until they press enter on an empty line to stop input.

It's giving some trouble in that I can get the method run and I can input text but it wont close or save? I hit return after my text to go to a blank line and hit return again but it just moves onto another line.

I have written the following but can't get it working correctly.

My code:

 public void writeFile()
{
    String myString;
    clrscr();
    System.out.println("Begin typing: ");
    myString = Genio.getString();
    FileOutputStream outputStream = null;
    PrintWriter printWriter = null;
    // use a try-catch-finally block to catch file-related exceptions
    try
    {
        outputStream = new FileOutputStream("writing.txt");
        printWriter = new PrintWriter(outputStream); 
        printWriter.write(myString);
        printWriter.newLine();
        // write information to the file via the PrintWriter
        while (myString  != "")
        {
            printWriter.print(myString + " ");
        }
    }
    catch (IOException e)
    {

        System.out.println("Sorry, there has been a problem opening or writing to the file");
    }
    finally
    {

        if (printWriter != null)
        {
            printWriter.close();    
        }
    }
}   

If it's needed, Genio is the class that deals with user input:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Genio
{

public Genio()
{
}

private static String getStr() 
{
    String inputLine = "";
    BufferedReader reader = 
        new BufferedReader(new InputStreamReader(System.in));
    try 
    {
        inputLine = reader.readLine();
    }

    catch(Exception exc) 
    {
        System.out.println ("There was an error during reading: "
                            + exc.getMessage());
    }
    return inputLine;
}

public static int getInteger()
{
    int temp=0;
    boolean OK = false;

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Integer.parseInt(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Integer value needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);
    return(temp);
 }

public static float getFloat()
{
    float temp=0;
    boolean OK = false;

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Float.parseFloat(keyboard.readLine());
            OK = true;
        }


        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Number needed: ");
            } 
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);

    return(temp);
 }

public static double getDouble()
{
    double temp=0;
    boolean OK = false;
    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Double.parseDouble(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Number needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);

    return(temp);
 }

 public static char getCharacter()
 {
     String tempStr="";
     char temp=' ';
     boolean OK = false;
     do 
     {
         try
         {
             tempStr = getStr();
             temp = tempStr.charAt(0);
             OK = true;
         }

         catch (Exception eRef)
         {
             if (eRef instanceof StringIndexOutOfBoundsException)
             {
                 // means nothing was entered so prompt ...
                 System.out.print("Enter a character: ");
             }            
             else 
             {
                 System.out.println("Please report this error: "+eRef.toString());
             }
         }

     } while(OK == false);

     return(temp);
 }

 public static String getString()
 {
    String temp="";
    try
    {
        temp = getStr();
    }
    catch (Exception eRef)
    {
        System.out.println("Please report this error: "+eRef.toString());
    }
    return(temp);
 }     
}
DarkBlueMullet
  • 93
  • 1
  • 11

5 Answers5

1

You only read myString once, before the while loop starts.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
1

You don't compare strings with == or !=

Change while (myString != "") to while (!myString.equals(""))

Rishi Dua
  • 2,296
  • 2
  • 24
  • 35
1

You class works fine for the most part. I fixed the problematic part for you:

// write information to the file via the PrintWriter
while (!myString.equals(""))
{
    myString = Genio.getString();
    printWriter.print(myString + "\n");
}

First the condition inside the while was incorrect. MyString has to be compared using the equals operator (or using the isEmpty method).

Second, you need to keep reading into myString inside the loop, otherwise you get an infinite loop and it will never exit.

Third, you want want to add newlines to the output file, so I added them.

Jeronimo Backes
  • 6,141
  • 2
  • 25
  • 29
  • Thank you for that. What you gave me works in that it does create and save the file. However, nothing happens to let me know that it has actually worked (I checked the folder and found the file there). Should I just add an println statement after the loop and ask the user if they wish to exit? I thought that the 'section' would actually take care of this for me? – DarkBlueMullet Nov 17 '14 at 12:25
  • I would change the condition in the while statement to `while (!myString.equals("quit"))`. This way when the user actually types the word "quit" the program will exit. You can write something "file written successfully" before the exception catch. – Jeronimo Backes Nov 17 '14 at 12:53
  • you should always also check for nulls first if using equals: if(myString!=null && !myString.equals("")) to avoid null pointer exception – MihaiC Nov 17 '14 at 13:14
  • Not if the `Genio.getStr()` method ensures null is never returned (which is better than putting null checks everywhere) – Jeronimo Backes Nov 17 '14 at 13:20
1

You have an infinite loop, because you only read myString before you enter the while loop, so your condition will never be false. Also, as Rishi Dua said, you can't compare strings with the usual == ou != operators, you have to use either .equals() or .isEmpty.

brlaranjeira
  • 367
  • 2
  • 11
1

Comparing == and equals method.

Since java.lang.String class override equals method, It return true if two String object contains same content.
But,
== will only return true if two references are pointing to same object.

Modified code:

while (! myString.equals("")){
     // Write your code here
      myString = Genio.getString();
      printWriter.print(myString + "\n");
}
atish shimpi
  • 4,873
  • 2
  • 32
  • 50