Hello everyone,
it seem like I'm now stuck at the second exercise in the next chapter of my java book which is about file processing(The Scanner/PrintStream classes mainly). After trying to find a way for hours I decided to ask in here.
The exercise says:
Write a method called wordWrap that accepts a Scanner representing an input file as it's parameter and outputs each line of the file to the console, word-wrapping all lines that are longer than 60 characters. For example, if a line contains 112 characters, the method should replace it with two lines: one containing the first 60 characters and another containing the final 52 characters. A line containing 217 characters should be wrapped into four lines: three of length 60 and a final of length 37.
What I've written so far is:
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Wrap { public static void main(String[] args0){ Scanner in = null; try{ in = new Scanner(new File("input.txt")); } catch (FileNotFoundException e){ System.out.println("File not Found"); } wordWrap(in); } public static void wordWrap(Scanner input){ String data = ""; while(input.hasNextLine()){ data = input.nextLine(); printText(data); } } public static void printText(String a){ Scanner temp = new Scanner(a); while(temp.hasNextLine()){ String line = temp.nextLine(); if(line.length() < 60){ System.out.println(line); }else { int i = 0; while(i < line.length()){ int j = 0; while(j < 60){ System.out.print(line.charAt(j)); j++; } System.out.println(); i +=60; } } } } }
And the output is this:
As you can see when the line in the txt is big enough for 3 lines, it just copies the first 60 chars again for 3 times.
When the line should be split in 2 lines it splits but still copy the same thing over again.
The lines that are under 60 characters are printed fine.
I think I've done something wrong with the loops n counting. Can someone tell me what I'm doing wrong and what I should correct to make it work right?