我正在开发一个Java程序,我有一个包含100行的data.csv文件。我想随机选择10行。数据如下所示:
T1 T2 T3 T4 T5
1 1.0 1 0 1
1 1.0 0 0 1
0 0.0 1 1 0
我已设法使用以下代码读取CSV文件:
public static void main(String[] args) throws IOException {
try
{
Scanner readIn = new Scanner (new File ("data.csv") );
while ( readIn.hasNext() )
{
line = readIn.nextLine();
str = line.split(",",-1);
}
readIn.close();
}
catch (ArrayIndexOutOfBoundsException ob)
{
System.out.println("File not found..." );
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
答案 0 :(得分:0)
更新了带有重复号码检查的代码:
int j=0;
Map<Integer,Integer> numberMap=new HashMap<Integer,Integer>();
SecureRandom random = new SecureRandom();
while(j!=10)
{
int row = random.nextInt(list.size());
if(!numberMap.containsKey(Integer.valueOf(row)))
{
numberMap.put(Integer.valueOf(row), Integer.valueOf(row));
System.out.println("Row "+row+"="+list.get(row));
j++;
}
}