0

I have a program that ask the user questions and stores them into an arraylist. I want to take my text file and replace the words ending with ] with the words from my arraylist from earlier. Here is just a piece of my code where I scanner the text file and find the words ending with ] and prints them. (Sorry if my code is a little cluttered, I'm still a bit new to java.)

//Scanning the chosen story file for story and custom words
    Scanner sf = new Scanner(new File("vacation.txt"));

    while (sf.hasNextLine()) {
    String current = sf.nextLine();

    String all_words[]; 
    all_words = current.split(" ");

    List<String> mywordList = new ArrayList<String>(all_words.length);
    for (String s:all_words) {
        mywordList.add( s );
    }
    for (String s : mywordList)
    {
        if (s.endsWith("]"))
        System.out.print( s + " " );
2Cold4u
  • 35
  • 4
  • Do you want to update your text file? – Abra May 15 '20 at 13:28
  • @Abra I think he wants to replace words ending with `]` in the text file. – darclander May 15 '20 at 13:44
  • @darclander Yes, that what I am trying to do. – 2Cold4u May 15 '20 at 13:47
  • 1
    OK, it looks as if you can identify words that end with `]`. So now, having such a word in hand, how will you choose a new word, from among the list of user responses, to replace it? – Kevin Anderson May 15 '20 at 13:47
  • @2Cold4u, since you can find the word ending with a `]` (which is an element in your `mywordlist`). I would suggest you modify the string to whatever you want. I believe stringbuilder is your best choice: https://stackoverflow.com/questions/6952363/replace-a-character-at-a-specific-index-in-a-string. And when that is done I assume you want to print the content of `mywordList` to the same file? Or if you want to completly set another string you can use an iterator and use the `Arraylist.set(index, value)` method. – darclander May 15 '20 at 13:50

0 Answers0