![](/img/trans.png)
[英]Count number of occurrences of a pattern in a text file using regex in Java
[英]Count the number of occurrences of integers in a file using ArrayLists
到目前为止,这就是我所拥有的,我只有一台扫描仪,可以读取文件中1-1000之间的1000个数字中的所有数字。我只是应该朝哪个方向停留一点。
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class ArrayListProb
{
public static void main(String[] args)throws IOException
{
File file = new File("number.txt");
Scanner reader = new Scanner(file);
ArrayList<Integer> numList = new ArrayList<Integer>(1000); //declare ArrayList with 1000 numbers
while(reader.hasNext()) //add the numbers to ArrayList
{
numList.add(reader.nextInt());
}
reader.close();
}
}
这是显示如何使用Scanner读取字符串值的示例:
public static void main(String[] args) throws IOException {
File file = new File("C:\\createtable.sql");
ArrayList<String> list = new ArrayList<String>(1000);
try (Scanner reader = new Scanner(file)) {
while (reader.hasNext()) // add the numbers to ArrayList
{
list.add(reader.next());
}
}
System.out.println(list);
}
您可以将整数读取为String值并将其解析为Integer。
Array-list不支持这种方法的整数,因此您有两种选择1)您可以使用Map代替Arraylist,然后执行以下代码。
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
while (inputFile.hasNext()){
Integer next = inputFile.nextInt();
if (myMap.containsKey(next)){
myMap.put(next, myMap.get(next) + 1);
}else{
myMap.put(next, 1);
}
}
2)或者您可以简单地将文件读取为字符串,然后按上述解决方案中所述将其解析为整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.