2015-07-04 77 views
3

我从文本文件中的单词已经打印出随机的,但我怎么能得到的话从文本中争抢。我有一个叫ScrambleWords的单独课程。我是 卡住从其他类调用scrambleWord方法。我的代码如下。我怎么能抢的话从一个文本文件后,已经随机地从文本选择一个字

public class WordShuffle extends ScrambleWords { 

    protected Scanner file; 
    protected ArrayList<String> words = new ArrayList<String>(); 

    public void openFile(){ 

     try { 
      file = new Scanner(new File("words.txt")); 


     } catch (FileNotFoundException e) { 
      System.out.println("File Not Found"); 
     } catch (Exception e){ 
      System.out.println("IOEXCEPTION"); 
     } 
    } 

    public void readFile(){ 

     Random r = new Random(); 

     while(file.hasNextLine()){ 
      words.add(file.nextLine()); 
      } 

      String randomWord = words.get(r.nextInt(words.size())); 
      Collections.shuffle(words); 
      System.out.println(randomWord); 

     //} 
    } 

    public void closeFile(){ 
     file.close(); 
    } 

    public static void main(String[] args) { 

     //ArrayList<String> inputString = words; 

     WordShuffle shuff = new WordShuffle(); 
     //ScrambleWords mix = new ScrambleWords(); 

     shuff.openFile(); 
     System.out.print("Before: "); 
     shuff.readFile(); 


     //System.out.println("After: "); 

     shuff.closeFile(); 
    } 

} 

public class ScrambleWords { 

    public static String scrambleWord(Random r, String inputString){ 

     //convert string to char array 
     char a[] = inputString.toCharArray(); 

     for(int i = 0; i < a.length-1; i++){ 
      int j = r.nextInt(a.length-1); 

      //swap letters 
      char temp = a[i]; a[i] = a[j]; a[j] = temp; 
     } 

     return new String(a); 
    } 

} 
+0

_I'm停留在呼吁从其它class_ ..你得到一个错误的scrambleWord方法,如果你尝试调用它还是有一些其他的问题??? – Codebender

+0

你能提供你的整个源代码,包括进口吗。然后我可以研究它,看看问题是什么。 – MooseMan55

+0

是啊当然,.............. WordShuffle类的输入是 – Alphanum3ric

回答

0

要真正争夺的话,你会使用像一个列表的中间数据结构来给自己整理的数据更快的方式会更好。

例子:

public static String scrambleWords(Random r, String curWord) { 
    List<Character> theWord = new ArrayList<>(curWord.length()); 
    for (int i = 0; i < theWord.size(); i++) { 
     theWord.add(curWord.charAt(i); 

    } 

    Collections.shuffle(theWord); 

    return new String(theWord.toArray(new Character[])); 
} 
+0

我怎么会打电话从其他类 – Alphanum3ric

+0

只需复制这种方法和上面的方法体粘贴到身体现有代码中的方法。 – andrewdleach

+0

好的thx为您的帮助sir – Alphanum3ric

相关问题