Reputation:
I am required to pass a file object to my constructor, and I am required to make a constructor in my method.
I am very confused as to why my code does not compile. It gives me several errors, and i am still struggling with the first one: sc cannot be resolved.
This is my class:
public class Reverser {
public Reverser(File file) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(file);
}
public void reverseLines(File outpr) {
PrintWriter pw = new PrintWriter(outpr);
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
new ArrayList < String > (Arrays.asList(words));
Collections.reverse(wordsarraylist);
if (wordsarraylist != null) {
String listString = wordsarraylist.toString;
listString = listString.subString(1, listString.length() - 1);
}
}
pw.write(listString);
}
}
and this is my main:
import java.util.*;
import java.io.*;
public class ReverserMain {
public static void main(String[] args) throws FileNotFoundException, IOException {
Reverser r = new Reverser(new File("test.txt"));
}
}
Upvotes: 1
Views: 273
Reputation: 3602
Are you adding more functions to this class? You can keep it simple with an approach like this:
public static void reverseLines(File inputFile, File outPutFile) {
try (Scanner sc = new Scanner(inputFile); PrintWriter pw = new PrintWriter(outPutFile)) {
while (sc.hasNextLine()) {
// your logic goes in here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You can use try-catch block with resources, will auto close the streams.
And when you are writing to the output file,if the file is already existing, do you want to append data or erase the contents of the file and write to a completely new file??
if you must use constructors:
public class Reverser {
File inputFile;
File outputFile;
public Reverser(File inputFile, File outputFile) {
this.inputFile = inputFile;
this.outputFile = outputFile;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void reverseLines() {
try (Scanner sc = new Scanner(inputFile); PrintWriter pw = new PrintWriter(outputFile)) {
while (sc.hasNextLine()) {
// your logic goes in here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Upvotes: 1
Reputation: 3795
Declare sc outside of the constructor :
Scanner sc = null ;
public Reverser(File file)throws FileNotFoundException, IOException{
sc = new Scanner (file);
}
Upvotes: 0