Friday, November 22, 2013

Java File write operation from Console

Write a JAVA Program which accepts lines of text from the console until 'stop' is entered and prints the lines of text it read.

Sample Input & Output :
Enter lines of text
Enter 'stop' to quit
---------------------
India's plans to wrap up a quick nuclear deal with Russia
The Prime Minister arrived here yesterday to a red carpet welcome
Top government sources said lawyers of both the sides have to clear the text of the agreement
stop

The lines you entered are :
--------------------------
India's plans to wrap up a quick nuclear deal with Russia
The Prime Minister arrived here yesterday to a red carpet welcome
Top government sources said lawyers of both the sides have to clear the text of the agreement

SOLUTION: 

 
import java.util.Scanner;

public class FileWrite {
 
 static public void main(String[] args){
  //Scanner object
  Scanner input = new Scanner(System.in);
  String[] text = new String[100];
  String temp;
  int i = 0;

  //Reading texts
  System.out.println("Enter lines of text\nEnter \'stop\' to quit\n");
  while((temp=input.nextLine()).compareTo("stop")!=0){
   text[i]=temp;
   i++;
  }
  //Printing string
  System.out.println("The lines you entered are :\n--------------------------");
  for ( int j=0; j < i; j++ ) {
   System.out.println(text[j]);
  }
 }//End main method.
}

No comments:

Post a Comment