Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

please help with java assingment. my code is below - i ' m unsure how to write the reversed contents into a new file -

please help with java assingment. my code is below - i'm unsure how to write the reversed contents into a new file - please help, my code is below: package assignment2;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) throws IOException{
ArrayList lines = new ArrayList<>();
//Read and process command line arguments
int files =0;//num of command line args that are files
String inFile ="";
String outFile ="";
if (args.length ==0){
usage();
System.exit(0);
}else{
//Read the command line arguments
for (int i =0; i< args.length; i++){
String arg = args[i];
if (Character.isDigit(arg.charAt(i))){
usage();
return;
}else{
//it is a file name
files++;
}
if (files ==1){
inFile=arg;
}else if (files ==2){
outFile = arg;
}
}
//construct the scanner and print writer onjects for the reading and writing
File inputFile = new File(inFile);
// open file, reverse each line, and add it to the array list
try(Scanner in = new Scanner(inputFile)){
while (in.hasNextLine()){
String line = in.nextLine();
String reversed = reverseString(line); //calling a method
lines.add(reversed);
}
}
//write the output to the txxt file
try(FileWriter out = new FileWriter(outFile)){
lines.forEach((line)->{
try {
out.write(line);
} catch (IOException e){
e.printStackTrace();
}
});
}
//here
}
}
// method reverses a string
static String reverseString(String r){
String s ="";
for (int i=r.length()-1; i>=0; i++){
char c = r.charAt(i);
s = s+c;
}
return s;
}
static void usage(){
System.out.println("Usage: java reverse infile outfile");
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Introduction To Database And Knowledge Base Systems

Authors: S Krishna

1st Edition

9810206208, 978-9810206208

More Books

Students also viewed these Databases questions

Question

Perform an Internet search. Discuss a company that uses EPLI.

Answered: 1 week ago

Question

How do you feel about employment-at-will policies? Are they fair?

Answered: 1 week ago