Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Java File Reader

I'm trying to make a word scrambler for a project in class. It needs to read in a .txt file and output a String with all of the words in the file; but scrambled. for example:

This is how the words should be scrambled.

Ignoring punctuation and leaving the first and last letter in place.

I'm having trouble reading in the file into an array. I was planning on using collections.shuffle to shuffle the inner layers by ignoring the first and last letter and randomizing the inner letters.

I don't know how to implement the file reader, but here is my scrambler for each word.

public static String shuffle(String input){
    input = "supercalifragilisticexpialidocious";
    int i = 0;
    ArrayList<Character> chars = new ArrayList<Character>(input.length());
    String output = "";
    char[] characters = input.toCharArray();
    char[] newWord = new char[input.length()];



    newWord[0] = characters[0];
    newWord[input.length()-1] = characters[input.length()-1];

    for (i=1; i < input.length()-1;i++ ) {
        chars.add(characters[i]);
    }

    System.out.println(chars);
    for (i = 1; i <= input.length()-2; i++)
    {
        Collections.shuffle(chars);
    }
    Character[] middle = chars.toArray(new Character[chars.size()]);
    for (i = 1; i < newWord.length - 2; i++)
    {
        newWord[i] = middle[i];
    }

    System.out.println(newWord);
    StringBuffer r= new StringBuffer(output);
    for (i = 0; i < newWord.length-1; i++)
    {
        r.append(newWord[i]);
    }

    return output;
}

This outputs saxupieipclflaurrtocslcidigaiiois like I want, but now I need a way to read the .txt file in and split it into separate words.

If anyone can help me that would be great. What I'm really looking for is if someone can help me with making a file reader for this.

like image 487
user2471416 Avatar asked Sep 13 '26 10:09

user2471416


1 Answers

use the filereader to read the file use the regex to split into words

    BufferedReader br = new BufferedReader( new FileReader( "file.txt" ) );
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while ( line != null ) {
            sb.append( line );
            sb.append( '\n' );
            line = br.readLine();
        }
        String everything = sb.toString();
        String[] words = everything.split( "[^\\w']+" );

        System.out.println( words );

    } finally {
        br.close();
    }
}
like image 82
Nambi Avatar answered Sep 16 '26 00:09

Nambi