Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Can't get lines to cut at 60 characters and continue on next line right

  1. #1
    Junior Member
    Join Date
    May 2011
    Posts
    21
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question Can't get lines to cut at 60 characters and continue on next line right

    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?


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Can't get lines to cut at 60 characters and continue on next line right

    Look at using some of the String class methods, like substring.

  3. #3
    Member
    Join Date
    Feb 2011
    Posts
    55
    My Mood
    Tolerant
    Thanks
    1
    Thanked 16 Times in 15 Posts

    Default Re: Can't get lines to cut at 60 characters and continue on next line right

    You'll want to follow Norm's advice and look at substring to do it a more efficient way. But to fix your way, make sure you look at value j in the print statement.

  4. #4
    Junior Member
    Join Date
    May 2011
    Posts
    21
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't get lines to cut at 60 characters and continue on next line right

    Thanks Norm and JJeng, I looked at substring as bot of you told me to look into. I seem to have forgotten that it existed but after getting so time to program I finally tried it out and rewrote the code and it worked nicely

    I moved to the next exercise which is a continuation of the same exercise but with some changes: Add a constant instead of hard-writing 60 into the code and write to a file instead of the console. Lastly make it so it writes to the same file it reads the text from.

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintStream;
    import java.util.Scanner;
     
    public class Wrap2 {
     
    	public static final int CUT = 60;
     
    	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");
    		}
    		PrintStream out = null;
    		try{
    			out = new PrintStream(new File("output.txt"));
    		} catch (FileNotFoundException e){
    			System.out.println("woooot");
    		}
     
    		wordWrap(in, out);
    	}
     
    	public static void wordWrap(Scanner input, PrintStream output){
     
    		String data = "";
    		while(input.hasNextLine()){
     
    			data = input.nextLine(); 
     
    			printText(data, output);
     
     
    		}
    	}
     
    	public static void printText(String a, PrintStream out){
     
    		Scanner temp = new Scanner(a);
     
    		String text = "";
    		while(temp.hasNextLine()){
    			String line = temp.nextLine();
     
    			int i = 0;
    			while(i < line.length()-1){
    				if(line.length()-1-i > CUT){
    					out.println(line.substring(i, i+CUT));
    				}
    				else{
    					out.println(line.substring(i, line.length()));
    				}
    				i +=CUT;
    			}
     
    		}
     
    	}
    }

    As you can see that code works perfect for writing into another file. The problem occurs when I change the output file name to the input file name. It ends rewriting nothing to the file it reads from making it a blank document.

    How can I write to the whole text from the file into the same with the changes that were made?

    A little related question: If I want to write the space-line in the text how do you do that? like this:

    "Mary was sitting in her chair.
    but then she found out that

    someone was jumping up and down outside her window."

    How do I find it via scanner in my code? I tried adding "\n" but in a String it disappears when you print it to a file. output.println() doesn't help either when it never finds the space-lines in my text (or automatically jumps over)
    Last edited by JavaN00b; May 19th, 2011 at 06:47 AM.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Can't get lines to cut at 60 characters and continue on next line right

    How can I write to the whole text from the file into the same with the changes that were made?
    One approach would be to write the text to a new file and then rename the old file and then the new file. Say add .new to the name of the original file, write the new text to it then rename the original file by adding .orig to its name (or delete it) and renaming the .new file by dropping the .new.
    How do I find it via scanner
    yes Scanner will skip over white spaces and new lines.
    Look at using the nextLine method. It reads everything up to a new line character. So you can assume that everything it reads had a newline and you can add it back in.

  6. #6
    Junior Member
    Join Date
    May 2011
    Posts
    21
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't get lines to cut at 60 characters and continue on next line right

    One approach would be to write the text to a new file and then rename the old file and then the new file. Say add .new to the name of the original file, write the new text to it then rename the original file by adding .orig to its name (or delete it) and renaming the .new file by dropping the .new.
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintStream;
    import java.util.Scanner;
     
    public class Wrap2 {
     
    	public static final int CUT = 60;
     
    	public static void main(String[] args0){
    		Scanner in =  null;
    		File i = new File("input.txt");
    		File o = new File("output.txt");
     
    		//Now the files should change names so it will still read from i which is "newinput.txt" while writing to o which is "input.txt"
    		i.renameTo(new File("newinput.txt"));
    		o.renameTo(new File("input.txt"));
     
    		try{
     
    			in = new Scanner(i);
    		} catch (FileNotFoundException e){
    			System.out.println("File not Found");
    		}
    		PrintStream out = null;
    		try{
     
    			out = new PrintStream(o);
    		} catch (FileNotFoundException e){
    			System.out.println("woooot");
    		}
     
    		wordWrap(in, out);
     
     
    	}
     
    	public static void wordWrap(Scanner input, PrintStream output){
     
    		String data = "";
    		while(input.hasNextLine()){
     
    			data = input.nextLine(); 
     
    			printText(data, output);			
     
    		}
    	}
     
    	public static void printText(String a, PrintStream out){
     
    		Scanner temp = new Scanner(a);
     
    		String text = "";
     
    		while(temp.hasNextLine()){
    			String line = temp.nextLine();
     
    			int i = 0;
    			while(i < line.length()-1){
    				if(line.length()-1-i > CUT){
    					out.println(line.substring(i, i+CUT));
    				}
    				else{
    					out.println(line.substring(i, line.length()));
    				}
    				i +=CUT;
     
    			}
     
    		}
     
    	}
    }

    I tried it but I keep getting a nullpointerexception while it's writing nothing except renaming the input to newinput.

    I seem to have misunderstood what you meant by that...or I'm doing something wrong.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Can't get lines to cut at 60 characters and continue on next line right

    I keep getting a nullpointerexception
    When you get errors, please copy and paste here the FULL contents of the console showing what you entered and the error message.

    After looking at your code:
    My suggestion was to
    First read in the input file and write it to a new file with the same name as the input file but with a .new added to the name.
    Then after the new file was written (you now have two files: the input and the output), rename the old/input file by adding an extension to the name such as .old.
    You Now have two files: the new one with .new and the old one renamed with .old
    Now rename the new one to have the same name as the old one did originally by removing the .new

    When you are done there are two files: the original one with the extension .old and the new one with the same name as the original input.

    The reason for this renaming is in case the program ends in the middle of the creating the new file, the original file will be untouched.
    Last edited by Norm; May 22nd, 2011 at 07:15 AM.

  8. #8
    Junior Member
    Join Date
    May 2011
    Posts
    21
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't get lines to cut at 60 characters and continue on next line right

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintStream;
    import java.util.Scanner;
     
    public class Wrap2 {
     
    	public static final int CUT = 60;
     
    	public static void main(String[] args0){
    		Scanner in =  null;
    		PrintStream out = null;
     
    		File i = new File("input.txt");
    		File o = new File("input.txt.new");
     
    		try{
    			in = new Scanner(i);
    		} catch (FileNotFoundException e){
    			System.out.println("File not Found");
    		}
     
    		try{
    			out = new PrintStream(o);
    		} catch (FileNotFoundException e){
    			System.out.println("woooot");
    		}
     
    		wordWrap(in, out);
     
     
    		//i as been read and o has been written too"
    		i.renameTo(new File("input.txt.old"));
     
    		o.renameTo(new File("input.txt"));
     
     
     
    	}
     
    	public static void wordWrap(Scanner input, PrintStream output){
     
    		String data = "";
    		while(input.hasNextLine()){
     
    			data = input.nextLine(); 
     
    			printText(data, output);			
     
    		}
    	}
     
    	public static void printText(String a, PrintStream out){
     
    		Scanner temp = new Scanner(a);
     
    		while(temp.hasNextLine()){
    			String line = temp.nextLine();
     
    			int i = 0;
    			while(i < line.length()-1){
    				if(line.length()-1-i > CUT){
    					out.println(line.substring(i, i+CUT));
    				}
    				else{
    					out.println(line.substring(i, line.length()));
    				}
    				i +=CUT;
     
    			}
     
    		}
     
    	}
    }

    First read in the input file and write it to a new file with the same name as the input file but with a .new added to the name.
    Done.
    Then after the new file was written (you now have two files: the input and the output),
    Done
    rename the old/input file by adding an extension to the name such as .old.
    This never happens
    You Now have two files: the new one with .new and the old one renamed with .old
    Now rename the new one to have the same name as the old one did originally by removing the .new

    When you are done there are two files: the original one with the extension .old and the new one with the same name as the original input.
    Nope I never get that I still have my input.txt and input.txt.new file till the end of program termination.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Can't get lines to cut at 60 characters and continue on next line right

    You should close the files that your were reading and writing when done with that step.

  10. The Following User Says Thank You to Norm For This Useful Post:

    JavaN00b (May 22nd, 2011)

  11. #10
    Junior Member
    Join Date
    May 2011
    Posts
    21
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Can't get lines to cut at 60 characters and continue on next line right

    THANKS A LOT!

    Since this chapter was about Scanner class which you so nicely reminded me (the renaming deal from before). Yes, quite embarassing that I didn't get that since it's mainly Scanner and File that's being used in these exercises.

    I figured that the answer was in the class even if the book mentions nothing about closing methods for Scanner. Because you told me that I should close I checked the class and saw there was indeed a close function for Scanner and PrintStream.

    It works perfect. Now I've learned that you need to close the files to rename them.

    Thanks for reminding me that only looking for the answer in the book by reading the chapter over and over isn't always the right answer.^^

    If I use different scanners to read the file should I close the file as soon as one scanner is done before the other scanner reads? Same with the writing?I was just wondering since it seems that the file is open and need to be closed before doing another action on it.

  12. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Can't get lines to cut at 60 characters and continue on next line right

    If you are done using a file, close it.

  13. The Following User Says Thank You to Norm For This Useful Post:

    JavaN00b (May 28th, 2011)

Similar Threads

  1. [SOLVED] Four arrays 32 line characters from text
    By sketch_flygirl in forum Collections and Generics
    Replies: 7
    Last Post: March 31st, 2011, 10:33 PM
  2. continue statements
    By monroe in forum Java Applets
    Replies: 1
    Last Post: March 20th, 2010, 06:26 PM
  3. How to make user press enter to continue in program?
    By BC2210 in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: October 3rd, 2009, 05:08 AM
  4. Reading a file line by line using the Scanner class
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: April 17th, 2009, 07:34 AM
  5. How to Read a file line by line using BufferedReader?
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: May 19th, 2008, 06:32 AM