Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

Java program starts by writing a piece of advice to the screen and asking the user to type in a different piece of advice

Write a  java program that gives and takes advice on program writing. The program
starts by writing a piece of advice to the screen and asking the user to type in a different
piece of advice. The program then ends. The next person to run the program
receives the advice given by the person who last ran the program. The advice is
kept in a text file and the content of the file changes after each run of the program.
You can use your editor to enter the initial piece of advice in the file so that the
first person who runs the program receives some advice. Allow the user to type in
advice of any length so that it can be any number of lines long. The user is told to
end his or her advice by pressing the Return key two times. Your program can then
test to see that it has reached the end of the input by checking to see when it reads
two consecutive occurrences of the character ‘\n’.

 

Answer:


import java.io.FileInputStream;
import java.util.Scanner;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;

public class Question6 {

   public static void main(String[] args){

      try {
		Scanner inputStream = new Scanner(new
			FileInputStream("advice.txt"));

		String line;
	 	while (inputStream.hasNextLine())
	 	{
			line = inputStream.nextLine();
	 		System.out.println(line);
	 	}
	 	inputStream.close();

	 	Scanner keyboard = new Scanner(System.in);

	 	System.out.println("Enter advice (hit return on empty line to quit):");

	 	PrintWriter outputStream = new PrintWriter(new
	    	FileOutputStream("advice.txt"));

	 	line = keyboard.nextLine();

	 	while (!line.equals(""))
	 	{
	 		outputStream.println(line);
	 		line = keyboard.nextLine();
	 	}
	 	outputStream.close();
      }
      catch (IOException e)
      {
		System.out.println("Error reading or writing files.");
      }
   }
} // Question6


About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!