1

嗨,我必须编写一个程序来计算候选人的数量以及他们从最好到最差的投票数。我编写了两个不同的类来使用 fileInputStream 和另一个使用扫描仪类并将其存储在 arraylist 中,但是老师在文本文件中的方式是一些选票在不同的行上,所以他们会去就像在一条线上,而选票在另一条线上。所以它是这样的:

//this is how the text appears in the text file and I was wondering if I could get all 
//the "votes" to look like the first one. 
<v> 5 4 3 2 1  
<v> 1 2 3 4 5 
<v>
1
2
3
5
<v>
5
2
4
1
3
4

2 回答 2

1

我认为你的老师是故意的。这里的诀窍是要意识到选票不是由新行分隔,而是由“V”分隔。您可以将此信息与 regex( Pattern ) 一起使用来得出解决方案。

于 2011-05-30T08:03:13.420 回答
0

如果您不想使用正则表达式,可以使用Scanner

if (scanner.hasNext("<v>")
  scanner.next();//ignore the "<v>"
if (scanner.hasNextInt())
  int vote1 = scanner.nextInt();//first vote
if (scanner.hasNextInt())
  int vote2 = scanner.nextInt();//second vote

例如,这将读取:

<v> 1
4

我不想破坏你做作业的“乐趣”,仅此而已。如果您有更多问题,请提出。

于 2011-05-30T09:45:01.650 回答