#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    6
    Rep Power
    0

    Write in console and then write to file


    Hi, I have a problem with writing to a file in Java. The thing is that if I use the command "story" in the console there will appear a few questions like "What is your name?" etc., and I'll be able to write my name in the console. Once the rest of the questions are answered, the summary of the so called story will simply appear as output in the console.

    But now I want to add an argument to the command "story", and there's the problem. In other words, if you write for ex. "story out.txt" (instead of just "story") I want the program to simply repeat the questions, but now I want the summary of the story to be written to the file out.txt, but I can't make it work. In one part I use a class named MakeStory including this code:

    Code:
    public class MakeStory {
    
    	// Name of character
        public static String name = "Eva";
        // Title of character
        public static String title = "the Teacher";
        // Description of appearance
        public static String appearance = "sporty";
    
        // Various attributes of the character
        public static boolean magic_bag = false;
        public static boolean happy = true;
        public static boolean secret = false;
    	
    	public static String generate() {
    		StringBuilder story = new StringBuilder(); 
    		
    		story.append("This is the story of ");
    		story.append(name + ", " + title + ". ");
    		story.append("Ever since the day " + name + " was born, ");
    		story.append(name + " looked " + appearance + ".\n\n");
    
    		if (magic_bag)
    			story.append(name + " had a magic bag. ");
    		if (happy) 
    			story.append(name + " was happy. ");
    		if (secret)
    			story.append(name + " had a secret. ");
    
    		story.append("\n\nSadly, there is not much else to say about ");
    		story.append(name + ".");
    
    		return story.toString();
    	}
    	
    }
    The other part of code I use looks like this at the moment:

    Code:
    private static void makeStory(String[] command) {
    		
    		Scanner in = new Scanner(System.in);
    		print("What is thy name? ");
    		MakeStory.name = in.nextLine();
    		print("What is thy title? ");
    		MakeStory.title = in.nextLine();
    		print("What is thy appearance? ");
    		MakeStory.appearance = in.nextLine();
    		print("Have you got a magic bag? (y/N)");
    		if (in.nextLine().equals("y")) {
    			MakeStory.magic_bag = true;
    		} else {
    			MakeStory.magic_bag = false;
    		}
    		print("Are you happy? (y/N)");
    		if (in.nextLine().equals("y")) {
    			MakeStory.happy = true;
    		} else {
    			MakeStory.happy = false;
    		}
    		print("Have you got a secret? (y/N)");
    		if (in.nextLine().equals("y")) {
    			MakeStory.secret = true;
    		} else {
    			MakeStory.secret = false;
    		}
    		
    		if (command.length == 1) {
    			
    			printLine(MakeStory.generate());
    		}
    		
    		else if (command[1].equals("out.txt")){
    			try {
    			FileWriter fw = new FileWriter("out.txt");
    			BufferedWriter bw = new BufferedWriter(fw);
    			bw.write(MakeStory.generate());
    			bw.close(); //Close the output stream
    			} 
    			catch (IOException e) {
    			e.printStackTrace();
    			
    		}
    I tried to apply an if statement, but I cant make the argument work, what am I doing wrong? :-(
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,022
    Rep Power
    1285
    Where is your main method?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    6
    Rep Power
    0
    Originally Posted by bullet
    Where is your main method?
    The makeStory method is from the class where I also have my main method. The main method looks like this:

    Code:
    public static void main(String[] args) throws IOException {
    
    		printLine("Welcome to the program.\nWrite ’quit’ to quit."); //Use printLine method for text output
    
    		helpData.put("help", "Displays a help massage."); //Give the "help"-key the value "Display a..." etc.
    		helpData.put("add", "Add a series of integers.");
    		helpData.put("quit", "Ends the program.");
    		helpData.put("story", "Generate a story."); //Uppgift 8
    
    		topLoop(); //Invoke while-loop
    
    		print("Quitting program, goodbye!");
    
    	}
    But I guess it doesn't say much, so here is all the code I'm working with in that class with the makeStory method at the bottom:

    Code:
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.HashMap;
    import java.util.Scanner;
    
    public class Interaction {	
    
    	static HashMap<String, String> helpData = new HashMap<String, String>();
    
    	public static void main(String[] args) throws IOException {
    
    		printLine("Welcome to the program.\nWrite ’quit’ to quit."); //Use printLine method for text output
    
    
    		helpData.put("help", "Displays a help massage."); //Give the "help"-key the value "Display a..." etc.
    		helpData.put("add", "Add a series of integers.");
    		helpData.put("quit", "Ends the program.");
    		helpData.put("story", "Generate a story."); //Uppgift 8
    
    		topLoop(); //Invoke while-loop
    
    		print("Quitting program, goodbye!");
    
    	}
    
    
    	public static void print(String a) { //Create method with string argument
    
    		System.out.print(String.valueOf(a)); //Print out string without line break
    	}
    
    	public static void printLine(String b) {
    
    		print(String.valueOf(b)+ "\n"); //Use print-method to add a line break after string-output
    
    	}
    
    
    	public static void topLoop() throws IOException {
    
    		while (true) //While true - loop forever
    		{ 	
    			print(">> ");
    
    
    			//Use BufferedReader-class to read in a string commando:
    
    			BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
    			String line = answer.readLine();
    
    			String[] input = line.split(" "); //Split String in array after space
    
    			// If input is "quit" and confirmed with "y":
    
    			if ("quit".equals(line)) { 	  
    				if (confirm() == true) { 
    					break; //Exit program
    				}
    			}
    			else if ("story".equals(line)) { //If commando is "story":
    				makeStory(input); //invoke makeStory-method
    			}
    			else { //Else: invoke handleInput-method:
    
    				handleInput(input);
    			}
    		}
    	}
    
    	public static boolean confirm() throws IOException {
    
    		print("Write 'y' if you really want to quit: "); //Confirm-text before exit
    
    		//Read in a string using scanner-class:
    
    		Scanner input = new Scanner(System.in);
    		String question = input.nextLine();
    
    		if ("y".equals(question)) { //If input is "y":
    			return true;
    		}
    		//Else:
    		return false;
    
    	}
    
    
    	public static void handleInput(String[] input) {
    
    		if ("add".equals(input[0])) { //If index 0 is "add":
    
    			add(input); //invoke add-method
    		}
    		else if ("help".equals(input[0])) { //If index 0 is "help":
    
    			help(input); //invoke help-method
    		}
    		else  { //If the command is something other than "add":
    
    			printLine("Unknown command '"+input[0]+"'"); //print out error msg and index 0/the command
    		}
    
    	}
    
    
    	public static void add(String[] command) {
    
    		try { //Try to sum ints after the commando "add"
    
    			int tal = 0;
    
    			for (int i = 1; i < command.length; i++) { //Loop starting from index 1 (to skip "add")
    
    				tal += Integer.parseInt(command[i]); //Sum ints and translate to int
    			}
    			printLine(String.valueOf(tal)); //Translate string to int and print out sum
    		}
    		catch(NumberFormatException e) { //Catch exception if input after "add" is not ints
    
    			printLine("Argument error: The 'add' command can only add integers."); //Print out error msg if not int
    		}
    
    	}
    
    
    	public static void help(String[] command) {
    
    		if (command.length == 1) { //If you only write "help":
    
    			printLine("Available commands:\nhelp\nadd\nquit");
    		}
    		else if (helpData.containsKey(command[1])) { //Else if input on index 1 is a key from HashMap:
    
    			printLine(helpData.get(command[1])); //print out value from specific key
    		}
    		else {
    			printLine("Unknown command '"+command[1] +"'"); //Else print out error msg and index 1
    		}
    	}
    
    
    	private static void makeStory(String[] command) {
    
    		Scanner in = new Scanner(System.in);
    		print("What is thy name? ");
    		MakeStory.name = in.nextLine();
    		print("What is thy title? ");
    		MakeStory.title = in.nextLine();
    		print("What is thy appearance? ");
    		MakeStory.appearance = in.nextLine();
    		print("Have you got a magic bag? (y/N)");
    		if (in.nextLine().equals("y")) {
    			MakeStory.magic_bag = true;
    		} else {
    			MakeStory.magic_bag = false;
    		}
    		print("Are you happy? (y/N)");
    		if (in.nextLine().equals("y")) {
    			MakeStory.happy = true;
    		} else {
    			MakeStory.happy = false;
    		}
    		print("Have you got a secret? (y/N)");
    		if (in.nextLine().equals("y")) {
    			MakeStory.secret = true;
    		} else {
    			MakeStory.secret = false;
    		}
    
    		if (command.length == 1) {
    
    			printLine(MakeStory.generate());
    		}
    
    		else if (command[1].equals("out.txt")){
    			try {
    				FileWriter fw = new FileWriter("out.txt");
    				BufferedWriter bw = new BufferedWriter(fw);
    				bw.write(MakeStory.generate());
    				bw.close(); //Close the output stream
    			} 
    			catch (IOException e) {
    				e.printStackTrace();
    
    			} 
    
    		}
    	}
    
    }//End class
  6. #4
  7. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,022
    Rep Power
    1285
    I believe this is your problem.

    Code:
    else if ("story".equals(line)) { //If commando is "story":
    				makeStory(input); //invoke makeStory-method
    			}
    			else { //Else: invoke handleInput-method:
    
    				handleInput(input);
    			}
    You call makeStory if the command is story.

    If the command is story out.txt, you call handleInput.

    Note that you can use the startsWith method.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    6
    Rep Power
    0
    Originally Posted by bullet
    I believe this is your problem.

    Code:
    else if ("story".equals(line)) { //If commando is "story":
    				makeStory(input); //invoke makeStory-method
    			}
    			else { //Else: invoke handleInput-method:
    
    				handleInput(input);
    			}
    You call makeStory if the command is story.

    If the command is story out.txt, you call handleInput.

    Note that you can use the startsWith method.
    Thanks, I think I'm on the right track now. I changed the code above to:

    Code:
    			if ("story".equals(line)) { //If commando is "story":
    				makeStory(line); //invoke makeStory-method
    			}
    			else if (line.endsWith("out.txt")) {
    				makeStory(line);
    			}
    			else { //Else: invoke handleInput-method:
    
    				handleInput(input);
    			}
    And the code in makeStory method to:

    Code:
    		if (command.equals("story")) {
    			printLine(MakeStory.generate());
    		}
    		else if (command.equals("out.txt")) {
    			
    			try {
    				FileWriter fw = new FileWriter("out.txt");
    				BufferedWriter bw = new BufferedWriter(fw);
    				bw.write(MakeStory.generate());
    				bw.close(); //Close the output stream
    			} 
    			catch (IOException e) {
    				e.printStackTrace();
    
    			}
    This saves the story to an out.txt file, but now my question is if I want to name the text file to whatever I want, and not just specifically as "out.txt", but as for ex. "hello.txt" etc. How do I do that? :S
  10. #6
  11. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,022
    Rep Power
    1285
    Use a variable to hold the name of the file.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    6
    Rep Power
    0
    Originally Posted by bullet
    Use a variable to hold the name of the file.
    Now it works, thank you! :-D

IMN logo majestic logo threadwatch logo seochat tools logo