Formated Input/Output in Java

In programming contest we have to use file to read data in different format and sometimes we have to write the output in a file. So, we have to know how to read from file. Here is the simple way to read from file and write as it in the another file.

import java.io.*;
import java.text.*;

public class brain {
    public static void main(String[] args)
    {
	try
	{
	RandomAccessFile file = new RandomAccessFile("brain.in", "r");
	String line;
	int inval = 0;
	int sum = 0;

	while((line = file.readLine()) != null)
	{
	inval = new Integer(line.trim()).intValue();
	sum = 0;
	if (inval == 0)
	System.exit(4);
	if (inval < 1)
		{
		for(int i = 1; i >= inval; i --)
	       sum += i;
		}
	else
		{
		for(int i = 1; i <= inval; i ++)
	       sum += i;
		}
	System.out.println("N = "+inval+"  Sum = "+sum);
		}

	System.out.println("Did not find trailing zero");
    }
	catch(Exception e)
	{
	System.out.println("Reading Error");
	}
    }
}

Add a Comment