java.io.PrintWriter + print(cArray:char []):void

时间:2015-01-25 15:43:22

标签: java arrays exception printing

我不知道如何写这一行:+print(cArray: char[]): void。我知道我想为我的家庭作业问题做些什么,只是这个阵列,这本书做了一个糟糕的工作解释。如果您想知道问题:编写程序以创建名为Excercise12_15.tx的文件(如果该文件不存在)。使用测试I / O将随机写入的100个整数写入文件。整数由文件中的空格分隔。从文件中读取数据并按递增顺序显示数据。

package WriteReadData;

import java.util.*;
public class WriteReadData {

    public static void main(String[] args) throws Exception
    {
        java.io.File file = new java.io.File("Excercise12_15.txt");
        final int SIZE = 100;
        int [] emptyArray = new int[SIZE];

        if ( file.exists())
        {
            System.out.print("File exists");
            System.exit(0);
        }//end if 

        try 
        {
            java.io.PrintWriter output = new java.io.PrintWriter(file);

            for (int i = 1; i < SIZE; i++)
            {
            emptyArray[i] = (int)(Math.random() * 100);
            output.print(emptyArray: int[]): void 
            }//end for 

        }//end try 
        catch 
        {
            output.close();
        }//end catch 
    }//end main 
}//end class

1 个答案:

答案 0 :(得分:0)

java.io.File file = new java.io.File("C:/Users/someUser/Desktop/Excercise12_15.txt");
    final int SIZE = 100;
    int [] emptyArray = new int[SIZE];

    if ( file.exists())
    {
        System.out.print("File exists");
        System.exit(0);
    }//end if 

//Place your output variable up here, so that it could be seen in the catch and finally block.

    java.io.PrintWriter output = null;
    try 
    {
        output = new java.io.PrintWriter(file);

        for (int i = 1; i < SIZE; i++)
        {
            emptyArray[i] = (int)(Math.random() * 100);
            //Your issuse was here, you didn't write the array to the file correctly
            output.print(emptyArray[i] + " "); 
        }//end for 

    }//end try 
    catch (Exception ex)
    {
        System.out.println(ex.getMessage());
    }//end catch
    finally{
        //Don't place the close in the catch block, do it in the finally, because it always
        //executes even when a catch happens.
         output.close();
    }

}

这是如何正确地将数组写入带空格的文本文件。