2012-04-23 97 views
1

下面是文本文件,我想以某种随机顺序在行中打印每个数字,以某种随机方式读取每行。我可以逐一读取每行,然后按顺序打印每行对应的数字,但是有什么方法可以以某种随机方式读取行,以便我可以按随机顺序打印所有数字。以随机的方式读取行,然后以随机顺序打印数字

Line1 1 1116 2090 100234 145106 76523 
Line2 1 10107 1008 10187 
Line3 1 10107 10908 1109 

任何建议,将不胜感激。以下是我编写的代码将按顺序读取行。

BufferedReader br = null; 

    try { 
     String sCurrentLine; 

     br = new BufferedReader(new FileReader("C:\\testing\\Test.txt")); 

     while ((sCurrentLine = br.readLine()) != null) { 
      String[] s = sCurrentLine.split("\\s+"); 
      for (String split : s) { 
       if(split.matches("\\d*")) 
       System.out.println(split); 
      } 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (br != null)br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
+0

1号线,将每个个体数是“1 ','1','1','6','2','0'等,还是'1116',2090','100234'等? – 2012-04-23 01:01:59

+0

对于第1行,数字是 - ''1''1116''2090''100234''145106''76523''和对于第2行,数字是 - '''''10107''1008''10187'' – AKIWEB 2012-04-23 01:04:17

回答

1

如果你的意思是重新排列各行的顺序类型的一些数组列表或数组,您可以使用Collections.shuffle:

while ((sCurrentLine = br.readLine()) != null) { 
    List<String> s = Arrays.asList(sCurrentLine.split("\\s+")); 
    Collections.shuffle(s); 
    for (String split : s) { 
     if (split.matches("\\d*")) { 
      System.out.println(split); 
     } 
    } 
} 

这将按顺序打印行,但每行中的数字将被混洗。

如果故意洗牌行的顺序为好,只是各行添加到ArrayList<List<String>>,洗牌的ArrayList,然后洗牌的每一行:

ArrayList<List<String>> allLines = new ArrayList<List<String>>(); 
while ((sCurrentLine = br.readLine()) != null) { 
    allLines.add(Arrays.asList(sCurrentLine.split("\\s+"))); 
    Collections.shuffle(allLines); 
    for (List<String> s : allLines) { 
     Collections.shuffle(s); 
     for (String split : s) { 
      if(split.matches("\\d*")) 
      System.out.println(split); 
     } 
    } 
} 
4

你不能“在一些随机的方式读取线”(当然,你可以,但是这将是可怕的!)

我建议顺序读取所有的行到一个集合和然后随机挑选1个(随机),直到收集为空。

您可以用类似的方法单独处理每一行:将所有数字解析为一个集合,然后将它们随机抽出。

例如(伪代码)

ArrayList lines = new ArrayList() 
while (! EOF) 
    lines.append(readLine) 

while(lines.size() > 0) 
    int index = Random(0, lines.size) 
    line = lines[index]; 
    lines.remove(index) 
    processLine(line) 
    // processLine does a similar thing to the above but with numbers 
    // on a line rather than lines in a file. 
+1

感谢John提供的建议,我用顺序读取文件的代码更新了我的问题。你可以给一些代码片段,可以将它们存储在集合中,然后它会随机选取它们,通过这些我可以更好地理解。 – AKIWEB 2012-04-23 01:05:24

0

存储区溢出的变量放到你想拥有的数字集合在文本文件中

+0

考虑重写你的答案。这不是很清楚。我建议你使用代码样式输入一小段代码来帮助回答问题。 – MADCookie 2012-04-23 20:00:06