String str = JOptionPane.showInputDialog("Search for a number from 0-9");
int intNum = Integer.parseInt(str);
try {
File file = new File("numbers.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int num;
int count = 0;
int position = 1;
while ((num = br.read()) != -1) {
if (Character.getNumericValue(num) == intNum) {
System.out.println(intNum + " occurred in " + position + " digit");
count++;
}
position++;
}
JOptionPane.showMessageDialog(null,
intNum + " was found " + count + " times in " + position + " digits", "Result",
JOptionPane.INFORMATION_MESSAGE);
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
numbers.txt是一个包含数千个以上数字的文本文件。用这个代码我只能搜索0-9之间的值,有没有什么方法可以搜索数字10,11,12。。。
澄清:我想在另一个号码中搜索一个号码(例如,1456452中出现了2个45)
2条答案
按热度按时间fdbelqdn1#
找到大于9的数字
使用bufferedreader非常好:
Scanner scanner;
try {
scanner = new Scanner(new File("your/file/path"));
while(scanner.hasNextLine()) {
while(scanner.hasNextInt()) {
int cur = scanner.nextInt();
if(cur > 9) {
System.out.println("Found number bigger than 9 ("+cur+")");
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try(BufferedReader br = new BufferedReader(new FileReader("your/file/path"))){
String s;
Scanner sc = new Scanner(System.in);
int lookFor = Integer.parseInt(sc.nextLine());
String read = br.readLine();
int len = String.valueOf(lookFor).length();
int found = 0;
for(int i = 0; i+len < read.length(); i++) {
String cur = read.substring(i, i+len);
if(Integer.parseInt(cur)==lookFor) {
found++;
}
}
}
System.out.println("Found: "+found);
wbgh16ku2#
您可以使用一些更奇特的东西来读取整个整数,而不仅仅是单个字符,例如scanner,而不是只使用bufferedreader。
这里有一个scanner.nextint()方法:
https://www.programiz.com/java-programming/scanner
(您也可以逐行读取并自行解析整数。)