简体   繁体   中英

Why is my MadLib txt file program not printing anything on each life after the right bracket “]”

I'm trying to create a program will allow a user to import a MadLib they created via text, import the file, and change the words in brackets that they type in.

What this program does is change the output of the txt file with a replaced word. However, everything after the replaced word disappears from the rest of each line.

I'll add my code and include comments on what I did, so you can see where the problem might be happening at.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFileChooser;



 public class BlanksStory {

ArrayList<String> story1 =new ArrayList<>();

public BlanksStory()
{
       File file=null;
      JFileChooser chooser = new JFileChooser();
       chooser.setDialogTitle("Load which file?");
       int result = chooser.showOpenDialog(null);
      if (result == JFileChooser.APPROVE_OPTION) {
       file = chooser.getSelectedFile();
  }
      String fileName= null;
      try {
        fileName= file.getCanonicalPath();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("Your file could not be read.");
    }

FileReader file1;
try {
    String line;
    file1 = new FileReader(file);
    BufferedReader bRead= new BufferedReader(file1);
    while((line=bRead.readLine())!=null){
        story1.add(line);    //Adds text file contents to the ArrayList
            }
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    System.out.println("File Not Found:  Please choose another file.");
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


    }
              public void play(){
              ArrayList<String> edited= new ArrayList<>();
    Scanner input= new Scanner(System.in);


    for(String x: story1){  //Reformats ArrayList to delete the brackets and 
    //commas, while putting each element on a new line to appear the same as 
    //in txt file. 
        StringBuffer buffer1= new StringBuffer();
        int startIndex=0;
        String z;
        for(int i=0; i<x.length();i++){
            if(x.charAt(i)=='['){
                int firstChar=i;
                while(x.charAt(i)!=']')
                    i++;
                    int lastIndex=i;

                    String word=x.substring(firstChar+1, lastIndex);
                    String replaceWord= x.substring(firstChar, lastIndex+1);
                    char firstLetter= word.charAt(0);

                    if(firstLetter=='a'|| firstLetter== 'e'|| firstLetter=='i'|| firstLetter=='o'||firstLetter=='u'){
                        System.out.println("Enter an "+word+": ");
                    }
                    else{
                        System.out.println("Enter a "+word+": ");
                    }  //Determines if vowel or consonant to choose a or an.
           //replaces the word with a new word entered by user
                String newWord= input.next();   
                z= x.replace(replaceWord, newWord); 


                buffer1.append(z.substring(startIndex, z.indexOf(newWord)+newWord.length()));
                startIndex=z.indexOf(newWord)+replaceWord.length()+1;
            }

        }
        edited.add(buffer1.toString());
    }
    for(String x:edited){
        System.out.println(x);
    }


}
public static void main(String [] args){

    BlanksStory madLib= new BlanksStory();
    madLib.play();

}
}

The txt file I used to test this program contains the following text...

    This is a [adjective] practice test.
    This test will [verb] if it works.

When asking for an adjective and for a verb, it works as it is supposed to. When I put in the word simple for adjective and run for verb, this is the output I get....

    This is a simple
    This test will run

It is supposed to read....

    This is a simple test.
     The test will run if it works.  

As you can see, it cuts everything off after the right bracket. I thought initially that maybe the last index wasn't set right, but when I told the user to choose a word of the type, it says the whole word with the correct index and no additional index of each line, so it does indeed end the replacement at the bracket and doesn't carry over to the rest of the sentence and cut that out as well with the replacement word.

The only other thing I was able to think of is the start index ran the loop again starting with the end of the word, so it didn't buffer through the rest of the text. However, I tried starting the index at the end of the loop at the last index of the element of story1, but I had no luck with that as it gives the same output.

I kept trying a few different things there, but it doesn't change the code at all. I commented out the startIndex at the last line of the loop all together, and it didn't change the program at all, so I'm wondering if there is any reason to even use it.

The first problem that I found is that the StringBuffer is not accepting an argument. The second problem I found is that the methods are taking from the String x and not from the StringBuffer buffer1.

I actually fixed this problem by calling the StringBuffer replace method for buffer1, putting in the first index, and the last index +1 in for the int arguments, and then the newWord for the replacement String. This is the code I came up with and it worked...

          public void play(){
    ArrayList<String> edited= new ArrayList<>();
    Scanner input= new Scanner(System.in);


    for(String x: story1){
  //  ^Takes the ArrayList of the story and reformats into a new string. 
  //  This takes the ArrayList story1, and removes the commas and brackets in between lines. 
        StringBuffer buffer1= new StringBuffer(x);

        for(int i=0; i<buffer1.length();i++){
            if(buffer1.charAt(i)=='['){
                int firstChar=i;
                while(buffer1.charAt(i)!=']')
    //^Searches for characters in the string that match brackets.  The loop is supposed to stop at the last bracket, replace the word, and then continue. 
                    i++;
                    int lastIndex=i;

                    String word=buffer1.substring(firstChar+1, lastIndex);

                    char firstLetter= word.charAt(0);

    /**String word is not used for replacement, but simply to read the word inside the brackets[].  
     * If word in brackets begins with a vowel, such as adjective, the prompt is...
     * Enter an adjective.  If the word begins with a consonant, such as verb, the prompt is...
     * Enter a verb.
     * The word entered by the user is put through the buffer, and it replaces the word inside the brackets[]. 
     */     
                    if(firstLetter=='a'|| firstLetter== 'e'|| firstLetter=='i'|| firstLetter=='o'||firstLetter=='u'){
                        System.out.println("Enter an "+word+": ");

                    }
                    else{
                        System.out.println("Enter a "+word+": ");

                    }
                    String newWord= input.nextLine();
                buffer1.replace(firstChar, lastIndex+1, newWord);

            }

        }
            //buffer1 is formatted into a toString(), and put into an ArrayList edited. 
        edited.add(buffer1.toString());

    }
    //ArrayList edited it put into a String format, called x, and then printed.  
    for(String x:edited){
        System.out.println(x);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM