2014-04-12 143 views
0

我想從方法getRandom中的ArrayList中獲取一個隨機詞。我的ArrayList是從一個文件加載的。然後我會在hang子手遊戲中使用這個詞。所以我想它要打印像* ****從arraylist中獲取一個隨機詞

import java.util.*; 
import java.io.*; 


public class Application { 
    private ArrayList<Pirateword> piratewords; 
    private Scanner input; 

    public Application(){ 
     input=new Scanner(System.in); 
     piratewords=new ArrayList<Pirateword>(); 

    } 

    public void runApplication() throws IOException { 

     String response; 
     String w; 
     do { 

      load("piratewords.txt"); 
      save("piratewords.txt"); 
      response=input.nextLine(); 


    } while (!((response.equals("q")|| (response.equals("q"))))); 
     System.out.println("Thank you for playing"); 
    } 




    public void load(String fileName) throws IOException{ 
     Scanner infile =new Scanner(new InputStreamReader(new FileInputStream(fileName))); 
     int num=infile.nextInt();infile.nextLine(); 
     for (int i=0;i<num;i++) { 
      String w=infile.nextLine(); 
      Pirateword p=new Pirateword(w); 
      piratewords.add(p); 
     } 
     infile.close(); 
    } 

    public void save(String fileName) throws IOException{ 
     PrintWriter outfile = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileName))); 
     outfile.println(piratewords.size()); 
     for (Pirateword p:piratewords) { 
      outfile.println(p.toString()); 
     } 
     outfile.close(); 
    } 

    public void getRandom() { 

} 
} 
+1

你知道如何產生隨機數嗎?如果是,則生成一個隨機數,然後得到該隨機索引的值 – stinepike

+0

@StinePike如果隨機數大於數組列表的大小,該怎麼辦?您應該提到隨機數必須在以下範圍內:0> random_number>數組大小。 –

回答

1
public String getRandom() { 
    return piratewords.get(new Random().nextInt(piratewords.size()); 
} 
+0

如果大小爲零,怎麼辦? – Braj

0

添加到您的構造函數。

Random gen = new Random(); 

在你的方法,用它來回報您的ArrayList中隨機字符串

public String getRandom() { 
    int index = gen.nextInt(piratewords.size()); 
    return piratewords.get(index); 
} 
+0

如果大小爲零,怎麼辦? – Braj

+0

然後你不能從列表中返回任何項目..添加檢查 – GoldRoger

0

嘗試用Collections.shuffle()如果沒有傷害洗牌原始列表中的項目。

注意:如果列表中有大量項目,請不要使用它。

if(piratewords.size()>0){ 
    Collections.shuffle(piratewords); 
    System.out.println(piratewords.get(0)); 
} 
+0

如何打印出控制檯中的隨機單詞? – user3430741

+0

我已更新我的帖子。只需調用'getRandom()'方法並打印返回的值即可。如果列表爲空,它將返回'null'。 – Braj

+0

對不起,打擾你,我是一個初學者.'getRandom(); { \t \t System.out.println(piratewords.get(0)); \t \t}'我試過這個,但是它沒有工作。我將原始文章的第一行中的字符串更改爲Pirateword,因爲它會進行其他編譯。 – user3430741

相關問題