【发布时间】:2017-01-22 23:27:33
【问题描述】:
我有一个文本文件和一个正则表达式,它可以提取整个文本中写入的所有数字。我能够匹配和提取这些数字,但我在尝试识别哪些提取的数字是素数时遇到了麻烦。
有人可以帮我吗?谢谢!
这是我的代码:
import java.util.Scanner;//Import Scanner class to read a file in the computer
import java.io.File;//Import File class to read a file in the computer
import java.io.FileNotFoundException;//Import FileNotFoundException class if case file is not found in the computer
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex2 {
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
//Display each word in INPUT_TEXT
Scanner INPUT_TEXT = new Scanner(new File("/Users/Matt/Desktop/regex2.csv"));//Create a Scanner Class and File Class to read a file from your computer.
INPUT_TEXT.useDelimiter(" ");//Divide file into several pieces by a space
if (INPUT_TEXT != null) {
System.out.println(INPUT_TEXT);
}
while(INPUT_TEXT.hasNext()) {
//Read each word
String TempString = INPUT_TEXT.next();
//Display all numbers.Eliminate comma, e.g., 1,200 -> 1200
String temp1 = TempString.replaceAll("[\\,]", "");//Create a String class temp1 that eliminates comma.
String pattern1 = "[0-9]+";//Create a String class pattern1 that stores the Regular Expression to match numbers.
Pattern r1 = Pattern.compile(pattern1);//Create Pattern class to compile pattern1.
Matcher m1 = r1.matcher(temp1);//Match each piece with the Regular Expression
if (m1.find()) {
System.out.print(m1.group() + " ");
//System.out.println(count);
count++;
// if count reaches 5, reset count and print new line
if (count == 5) {
count = 0;
System.out.println();
}
}
}
INPUT_TEXT.close();//Close your Scanner.
}
}
【问题讨论】:
-
您需要编写一个方法来确定某个输入数字是否为素数。确定整数 n 素数的唯一方法是从 1 到 \sqrt{n} 的试除法。
-
@ifly6 但如果可以使用正则表达式来完成,那不是很酷。
-
你误解了this question。此正则表达式不检查字符串是否包含素数。问题中的代码 builds 长度为 n 的字符串(例如,
***表示 n=3),然后使用正则表达式对其进行检查。 -
@DavidWallace 这是小事。我想要一个正则表达式来确定我的程序是否终止。 :)
-
@V1P3R 这个问题并不实际,难怪你不明白。恐怕您必须从字符串中解析一个数字,然后对其进行质数测试。看看这个问题:stackoverflow.com/questions/2385909/…