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 14 of 14

Thread: PrintStream, strings and reading from a file.

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    29
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default PrintStream, strings and reading from a file.

    I've gotten sort of stuck on my assignment for my Java class and I was wondering if anyone could point me in the right direction.

    The general idea of what is intended is that the computer will read an exterior file, and every time it stops at something like < noun > it will ask the reader basically "please input a: noun", so I first want it to find the instance of a < word > and read it, and then I want to be able to change that word to what the user inputted by creating a new file of this new story.

    So the original file would read 'Fred Meyers is < adjective >
    The console would say Please input a: adjective
    The user would input a word (let's say smart)
    And a new file would get the words as they're printed, so it would be Fred Meyers is smart in the new file.

    import java.util.*;
    import java.io.*;
    public class StoryGenerator {
    	public static void main(String[] args) {
    		readFile();
    	}
     
    	public static void readFile() {
    		double sum = 0.0;
    		try {	
    			System.out.println("Enter the name of your story file:");
    			Scanner scan = new Scanner(System.in);
    			Scanner file = new Scanner(new File(scan.next()));
    			while (file.hasNext()) {
    			String input = file.next();
    			if (input.startsWith("<") && input.endsWith(">")) {
    					String word = input.substring(1, input.length() - 1);
    					System.out.println("Please input a: " + word);
    				}
    			}
    		}
    		catch (java.io.FileNotFoundException ex) {
    			System.out.println("File not found.");
    			System.exit(-1);
    		}
    	}
     
    }


    So I figured out how to print the < noun > thing (and edited the above code), for all except the word with the space (i.e. <your name> ), So I need help figuring out how to get the <your name> to show up, I am also stuck on how to replace it and write a new document (Although I think that I am supposed to reassign the string in the if loop to the new word, and there should probably be PrintStream somewhere.)

    EDIT:

    Okay, I got "your name" to show up by using a nested if loop.

    import java.util.*;
    import java.io.*;
    public class StoryGenerator {
    	public static void main(String[] args) {
    		readFile();
    	}
     
    	public static void readFile() {
    		double sum = 0.0;
    		try {	
    			System.out.println("Enter the name of your story file:");
    			Scanner scan = new Scanner(System.in);
    			Scanner file = new Scanner(new File(scan.next()));
    			while (file.hasNext()) {
    			String input = file.next();
    			if (input.startsWith("<") && input.endsWith(">")) {
    					String word = input.substring(1, input.length() - 1);
    					System.out.println("Please input a: " + word);
    				}
    			if (input.startsWith("<your")) {
    				String word = input.substring(1, input.length());
    				System.out.print("Please input a: " + word);
    				input = file.next();
     
    				if (input.startsWith("name>")) {
    					word = input.substring(0, input.length() - 1);
    					System.out.println(" " + word);
    				}
    			}
    			}
    		}
    		catch (java.io.FileNotFoundException ex) {
    			System.out.println("File not found.");
    			System.exit(-1);
    		}
    	}
    }

    Now I need help figuring out how to replace that input and then print the story out to a new file (as stated above.)

    EDIT: Figured out how to replace the input, now I just need to know how to PrintStream as the story goes on.

    current code:

    import java.util.*;
    import java.io.*;
    public class StoryGenerator {
    	public static void main(String[] args) {
    		readFile();
    	}
     
    	public static void readFile() {
    		double sum = 0.0;
    		try {	
    			System.out.println("Enter the name of your story file:");
    			Scanner scan = new Scanner(System.in);
    			Scanner file = new Scanner(new File(scan.next()));
    			while (file.hasNext()) {
    			String input = file.next();
    			if (input.startsWith("<") && input.endsWith(">")) {
    					String word = input.substring(1, input.length() - 1);
    					System.out.println("Please input a: " + word);
    					input.replaceAll(input, scan.next());
    				}
    			if (input.startsWith("<your")) {
    				String word = input.substring(1, input.length());
    				System.out.print("Please input a: " + word);
    				input = file.next();
    				input.replaceAll(input, "");
     
    				if (input.startsWith("name>")) {
    					word = input.substring(0, input.length() - 1);
    					System.out.println(" " + word);
    					input.replaceAll(input, scan.next());
    				}
     
    			}
    			}
    		}
    		catch (java.io.FileNotFoundException ex) {
    			System.out.println("File not found.");
    			System.exit(-1);
    		}
    	}
    }


  2. #2
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: PrintStream, strings and reading from a file.

    If the contents are not too long you can store the entire story in memory and then write it out at the end. If you are allowed I suggest using a FileWriter as it is easier to use. If you need to write segments out one at a time then FileWriter is definitely a good choice as it allows you to add to the contents of a file.
    Improving the world one idiot at a time!

  3. #3
    Junior Member
    Join Date
    Oct 2013
    Posts
    29
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: PrintStream, strings and reading from a file.

    Unfortunately, FileWriter is not something I've learned and I have any idea how to implement to the above code, likewise the file we have to use to bring the story has to be declared early on (when they scan for the file name).

    I tried using a FileWriter, more as an experiment, and I have this:

    import java.util.*;
    import java.io.*;
    public class StoryGen {
    	public static void main(String[] args) throws IOException {
    			Scanner scan = new Scanner(System.in);
    			Scanner file = new Scanner(new File(scan.next()));
    			FileWriter f = new FileWriter(new File("outfile.txt"));
    			while (file.hasNext()) {
    				String input = file.next();
    				if (input.startsWith("<") && input.endsWith(">")) {
    						String word = input.substring(1, input.length() - 1);
    						System.out.println("Please input a: " + word);
    						input.replaceAll(input, scan.next());
    				}
    				if (input.startsWith("<your")) {
    					String word = input.substring(1, input.length());
    					System.out.print("Please input a: " + word);
    					input = file.next();
    					input.replaceAll(input, "");
    					if (input.startsWith("name>")) {
    						word = input.substring(0, input.length() - 1);
    						System.out.println(" " + word);
    						input.replaceAll(input, scan.next());
    					}
    				}
    			}
    			f.close();
    	}
    }

    Unfortunately, outfile is blank when I open it. Help?

  4. #4
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: PrintStream, strings and reading from a file.

    Whenever you use a Writer you must close/flush it when you are finished. Otherwise data is left in the buffer.
    Improving the world one idiot at a time!

  5. #5
    Junior Member
    Join Date
    Oct 2013
    Posts
    29
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: PrintStream, strings and reading from a file.

    Doesn't f.close() near the end of the code do the flush/closing of the FileWriter? It still only creates a blank document instead of writing the text.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: PrintStream, strings and reading from a file.

    Comment: Using a single letter like f for a variable name makes it hard to "Search" the source to see where the variable is used. A longer, unique name would make it easier.

    Where is the variable: f used in the code? Where does the code call the FileWriter's methods?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Oct 2013
    Posts
    29
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: PrintStream, strings and reading from a file.

    So I did realize that I wasn't printing anything out to the filewriter, and I renamed it like above so that my code is now this:

    import java.util.*;
    import java.io.*;
    public class StoryGenB {
    	public static void main(String[] args) throws IOException {
    			try {
    			Scanner scan = new Scanner(System.in);
    			Scanner file = new Scanner(new File(scan.next()));
    			FileWriter filewriter = new FileWriter(new File("outfile.txt"));
    			while (file.hasNext()) {
    				String input = file.next();
    				if (input.startsWith("<") && input.endsWith(">")) {
    						String word = input.substring(1, input.length() - 1);
    						System.out.println("Please input a: " + word);
    						word = input.replace(input, scan.next());
    						filewriter.write(word);
    				}
    				if (input.startsWith("<your")) {
    					String word = input.substring(1, input.length());
    					System.out.print("Please input a: " + word);
    					input = file.next();
    					input.replaceAll(input, "");
    					if (input.startsWith("name>")) {
    						word = input.substring(0, input.length() - 1);
    						System.out.println(" " + word);
    						word = input.replace(input, scan.next());
    						filewriter.write(word);
    					}
    				}
    				else { filewriter.write(input);}
    				filewriter.write(" ");
     
    			}
    			filewriter.close();
    		}
    	catch (java.io.FileNotFoundException ex) {  
    		System.out.println("File not found.");  
    		System.exit(-1);  
            }  
     
    	}
     
    }

    Now, my new problem is that the words that are taken care of in the first if loop (the ones starting and ending with <> are being printed first replaced, then printing out the <word> as well.

    Once there was a chick<gender> named Sam . [He/She] was a wizard! One day, an owl came with a letter. It said, "Please come to Kalamazoo<city> and learn magic. You will need to bring kitten<noun> , puppy<noun> and a car<noun> . You may also bring one pet. Your ticket for the <the city again> Express <mode of transport> is enclosed!" Sam went to Stiches<store> and bought a red<colour> giraffe<animal> and named it Clore<name> . Once the shopping was done, Sam was ready for Magic School! [He/She] hopped on the <the mode of transport again> and never looked back!

    So for all the words in the first if statement, it is printing that word and the replaced word.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: PrintStream, strings and reading from a file.

    You don't need to write anything to a file to test the String replacement logic.
    Write a small test program
    Define a String with the delimited Strings.
    Write the logic to do the replacements.
    Print out the results to see if it is working.

    A String is immutable. All the methods that "change" a String return a new String with the changes.
    Look at how the code uses the String class's methods.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Oct 2013
    Posts
    29
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: PrintStream, strings and reading from a file.

    So I fixed that so the current code is this:
    import java.util.*;
    import java.io.*;
    public class StoryGenB {
    	public static void main(String[] args) {
    		file();
    	}
     
    	public static void file() {
    			try {
    			Scanner scan = new Scanner(System.in);
    			Scanner file = new Scanner(new File(scan.next()));
    			FileWriter filewriter = new FileWriter(new File("outfile.txt"));
    			while (file.hasNext()) {
    				String input = file.next();
    				if (input.startsWith("<") && input.endsWith(">")) {
    						String word = input.substring(1, input.length() - 1);
    						System.out.println("Please input a: " + word);
    						word = scan.next();
    						filewriter.write(word);
    						input = file.next();
    						filewriter.write(" ");
    				}
    				if (input.startsWith("<")) {
    					String word = input.substring(1, input.length());
    					System.out.print("Please input a: " + word);
    					input = file.next();
    					input.replace(input, "");
    					if (input.endsWith(">")) {
    						word = input.substring(0, input.length() - 1);
    						System.out.println(" " + word);
    						word = scan.next();
    						filewriter.write(word);
    					}
    				}
    				else { filewriter.write(input);}
    				filewriter.write(" ");
     
    			}
    			filewriter.close();
    		}
    	catch (java.io.FileNotFoundException ex) {  
    		System.out.println("File not found.");  
    		System.exit(-1);  
            }  
            catch (java.io.IOException ex) {
            	System.out.println("File not created");
            	System.exit(-1);
     
    	}
    	}
     
    }
    I found that <your name> isn't the only one with spaces that I need to replace, so now I'm trying to figure out a way to make it so that it will keep going if the string has a "<" until it finds a ">" Any suggestions?

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: PrintStream, strings and reading from a file.

    The String class has methods for finding Strings within another String. Use a method to Find the "<" and then find the ">".
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Oct 2013
    Posts
    29
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: PrintStream, strings and reading from a file.

    So I have this:

    import java.util.*;
    import java.io.*;
    public class StoryGenB {
    	public static void main(String[] args) {
    		file();
    	}
     
    	public static void file() {
    			try {
    			Scanner scan = new Scanner(System.in);
    			Scanner file = new Scanner(new File(scan.next()));
    			FileWriter filewriter = new FileWriter(new File("outfile.txt"));
    			while (file.hasNext()) {
    				String input = file.next();
    				if (input.startsWith("<")) {
    					int start = input.indexOf("<");
    					int end = input.indexOf(">");
    					String word = input.substring(start +1, end);
    					System.out.println("Please input a: " + word);
    					word = scan.next();
    				}
    				else {filewriter.write(input);}
    				filewriter.write(" ");
     
    			}
    			filewriter.close();
    		}
    	catch (java.io.FileNotFoundException ex) {  
    		System.out.println("File not found.");  
    		System.exit(-1);  
            }  
            catch (java.io.IOException ex) {
            	System.out.println("File not created");
            	System.exit(-1);
     
    	}
    	}
     
    }

    The index is supposed to find the start ("<") and the next index is supposed to find the end (">"), however I am unsure how to make it keep looking to find the end, as when the above code is compiled it gives a string index out of range error.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: PrintStream, strings and reading from a file.

    Can you make a small test program with a String that has the < and > and has the logic you are working with?
    The FileWriter class isn't needed for debugging problems parsing a String.

    string index out of range error.
    That sounds like a runtime error. You don't get that kind of error from a compiler. Copy the full text of the error message and paste it here.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Oct 2013
    Posts
    29
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: PrintStream, strings and reading from a file.

    Here is the error message I am getting:
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
    ex out of range: -1
            at java.lang.String.substring(String.java:1911)
            at StoryGenF.file(StoryGenF.java:17)
            at StoryGenF.main(StoryGenF.java:5)

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: PrintStream, strings and reading from a file.

    At line 17 the code has used an index with the value -1 which is invalid. Valid indexes range in value from 0 to the length of the String -1. Look at line 17 and see why it is using an index of -1.

    The code should test the value returned by the indexOf() method to be sure it is valid. See the API doc for a description of the values it will return.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 3
    Last Post: December 2nd, 2011, 11:53 AM
  2. Having problem to stop reading strings
    By scsa316 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 18th, 2011, 10:24 AM
  3. Replies: 36
    Last Post: July 25th, 2011, 10:27 AM
  4. reading content of the text file, splitting it into strings
    By Dodo in forum File I/O & Other I/O Streams
    Replies: 7
    Last Post: January 6th, 2011, 07:57 PM
  5. PrintStream not printing in file
    By rrahulvverma in forum File I/O & Other I/O Streams
    Replies: 6
    Last Post: November 2nd, 2010, 05:32 PM