Write a program that takes four command line arguments: start, stop, step, and f
ID: 3677887 • Letter: W
Question
Write a program that takes four command line arguments: start, stop, step, and file. The first three arguments are nonnegative integers and the fourth is a string. The program is to write numbers to the file specified in the file argument, starting with start, increment by step each time, all the way through stop. Write the numbers ten per line in the file.
Sample Run: Command Prompt$ ./a.out 0 999 20 file.txt
Should produce a file.txt like:
0 20 40 60 80 100 120 140 160 180
200 220 240 260 280 300 320 340 360 380
400 420 440 460 480 500 520 540 560 580
600 620 640 660 680 700 720 740 760 780
800 820 840 860 880 900 920 940 960 980
Explanation / Answer
import java.util.Scanner;
import java.io.*;
public class WriteFile
{
public static void main(String args[])
{
int count=o;
Scanner in = new Scanner(System.in);
System.out.printf("Please Enter start, stop, step values and file name ");
//reading all values store in appropriate variable
int start=in.nextInt();
int stop=in.nextInt();
int step=in.nextInt();
String file=in.next();
if(start<0||stop<0||step<0)
{
System.out.printf("Please Enter positive values ");
System.exit(0);
}
try{
// Create a file for file variable given by the user
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
//writing values into file.
for(i=start;i<stop;i=i+step)
{
count++;
out.write(i);
//printing 10 values per line
if(count%10==0)
out.newline();
}
//Close the output stream
out.close();
}
catch (Exception e)
{//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}//main
}//class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.