So i have this so far and im not sure whats wrong but im supposed to allow the u
ID: 3657914 • Letter: S
Question
So i have this so far and im not sure whats wrong but im supposed to allow the user to specify the file name on the command line. [if the user doesn't specify any file name, then prompt the user for the name.] import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class AddLineNumbers2 { public static void main(String[] name) throws FileNotFoundException //this exception will allow the program to inform users if the file does not exist { String inputFileName = name[0]; String outputFileName = name[1]; //reads the input from the command line and stores the file names File reader = new File(inputFileName); Scanner in = new Scanner(reader); PrintWriter out = new PrintWriter(outputFileName); //allows output to be stored in output file int lineNumber = 1; while (in.hasNextLine()) //loops while input file has lines { String line = in.nextLine(); //reads lines from input file out.printf("/* %d */%s ", lineNumber, line); //adds line numbers to file and stores in output file lineNumber++; } out.close(); //closes output file } }Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class AddLineNumbers2
{
public static void main(String[] name) throws FileNotFoundException
//this exception will allow the program to inform users if the file does not exist
{
String inputFileName;
String outputFileName;
// check if arguments were given by command line
if(name.length >= 2)
{
inputFileName = name[0];
outputFileName = name[1];
}
// otherwise prompt for input
else
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter the input file name: ");
inputFileName = kb.nextLine().trim();
System.out.print("Enter the output file name: ");
outputFileName = kb.nextLine().trim();
}
//reads the input from the command line and stores the file names
File reader = new File(inputFileName);
Scanner in = new Scanner(reader);
PrintWriter out = new PrintWriter(outputFileName);
//allows output to be stored in output file
int lineNumber = 1;
while (in.hasNextLine())
//loops while input file has lines
{
String line = in.nextLine();
//reads lines from input file
out.printf("/* %d */%s ", lineNumber, line);
//adds line numbers to file and stores in output file
lineNumber++;
}
out.close();
//closes output file
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.