vendredi 27 novembre 2015

How to read in a word from .txt using Java Jframe and choose a random word from file

In my program I need to read a word from a .txt file that contains lot of words (in different lines) and my program should be able to choose a random word from the .txt file. I did lot of research on this but somehow it doesnt worked for me not sure if because i'm Using Jframe. Greatly appreciate your help and guidance.

I am able to choose a random words from my program but have no luck with reading a random word from .txt file.

public class GuessForm extends javax.swing.JFrame {
 String[] FindWord1 = {"hello", "hey", "well", "story", "fight","punch"};
 int idx = new Random().nextInt(FindWord1.length);
 String FindWord = (FindWord1[idx]);
 int wordL = FindWord.length();

I have tried using several methods but nothing seems to worked.

import java.util.Random;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner; 

public class GuessForm extends javax.swing.JFrame {
   String filename = "H:\\lol.txt";
   File file = new File (filename);
   Scanner input = new Scanner new FileReader(file));
   while (input.hasNext()){
   String FindWord1 = input.next();}
   int idx = new Random().nextInt(FindWord1.length);
   String FindWord = (FindWord1[idx]);
   int wordL = FindWord.length(); }




Aucun commentaire:

Enregistrer un commentaire