0

So I need to make a program that reads a file containing text and then adds line numbers to each line. What I have so far prints out the line number but instead of just printing out each line, it prints all of the text in each line. How can I just have it so it prints out the line?

Here's the code I have so far:

public static void main(String[] args) throws FileNotFoundException {
    try {
        ArrayList<String> poem = readPoem("src\\P7_2\\input.txt");
        number("output.txt",poem);
    }catch(Exception e){
        System.out.println("File not found.");
    }
}

public static ArrayList<String> readPoem(String filename) throws FileNotFoundException {
    ArrayList<String> lineList = new ArrayList<String>();
    Scanner in = new Scanner(new File(filename));
    while (in.hasNextLine()) {
        lineList.add(in.nextLine());
    }
    in.close();
    return lineList;
}
public static void number (String filename,ArrayList<String> lines) throws FileNotFoundException{
    PrintWriter out = new PrintWriter(filename);
    for(int i = 0; i<lines.size(); i++){
        out.println("/* " + i + "*/" + lines);
    }
    out.close();
}
user3342038
  • 63
  • 1
  • 4
  • 11

3 Answers3

1

Here is a shorter version of your program using new capabilities offered by Java 7; it supposes that you have a short enough source file:

final Charset charset = StandardCharsets.UTF_8;
final String lineSeparator = System.lineSeparator();

final Path src = Paths.get("src\\P7_2\\input.txt");
final Path dst = Paths.get("output.txt");

try (
    final BufferedWriter writer = Files.newBufferedWriter(src, charset, StandardOpenOption.CREATE);
) {
    int lineNumber = 1;
    for (final String line: Files.readAllLines(src, charset))
        writer.write(String.format("/* %d */ %s%s", lineNumber++, line, lineSeparator));
    writer.flush();
}
fge
  • 119,121
  • 33
  • 254
  • 329
  • 2
    System.lineSeparator() – Hakanai Apr 11 '14 at 23:13
  • added in Java 7 I think. :) Also when I took a closer look, it turns out you're only using it in String.format, so you might as well just put `%n` in the format string. – Hakanai Apr 11 '14 at 23:34
0

Use

out.println("/* " + i + "*/" + lines.get(i));

in place of

out.println("/* " + i + "*/" + lines);

You are printing complete list in each line.

Braj
  • 46,415
  • 5
  • 60
  • 76
0

i'd say this is your problem:

out.println("/* " + i + "*/" + lines); //this prints all the lines each loop execution

you can try using:

int i = 1; //or the first value you wish
for(String a : lines){
    out.println("/* " + i + "*/" + a);
    i++;
}
darthVader
  • 41
  • 1
  • 7