创建打开文件的方法,然后让用户写入文件然后在空行时按Enter键结束?

时间:2014-11-17 12:12:25

标签: java loops

我想创建一个打开文件进行写入的方法,然后提示用户输入文本行,直到他们按空行上的Enter键停止输入。

它给了一些麻烦,我可以运行方法,我可以输入文本,但它不会关闭或保存?我在文本后点击返回空白行并再次点击返回,但它只是移动到另一行。

我写了以下内容但无法使其正常工作。

我的代码:

 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();    
        }
    }
}   

如果需要,Genio是处理用户输入的类:

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);
 }     
}

5 个答案:

答案 0 :(得分:1)

myString循环开始之前,您只能阅读while一次。

答案 1 :(得分:1)

您不会将字符串与==或!=

进行比较

更改 while (myString != "")while (!myString.equals(""))

答案 2 :(得分:1)

你的课程大部分时间都很好。我为你解决了有问题的部分:

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

首先,内部条件不正确。必须使用equals运算符(或使用isEmpty方法)比较MyString。

其次,你需要继续读入循环内的myString,否则你会得到一个无限循环,它永远不会退出。

第三,你想要在输出文件中添加换行符,所以我添加了它们。

答案 3 :(得分:1)

你有一个无限循环,因为你只在进入while循环之前阅读myString,所以你的情况永远不会是假的。 此外,正如Rishi Dua所说,您无法将字符串与通常的== ou !=运算符进行比较,您必须使用.equals().isEmpty

答案 4 :(得分:1)

比较==equals方法。

由于java.lang.String类重写equals方法,如果两个String对象包含相同的内容,则返回true
但是,
如果两个引用指向同一个对象,==将仅返回true

修改后的代码:

while (! myString.equals("")){
     // Write your code here
      myString = Genio.getString();
      printWriter.print(myString + "\n");
}