2015-07-04 79 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

相關問題