我正在编写一个程序MultiplicationTable,它显示用户从命令行输入的乘法表,这样如果用户输入了MultiplicationTable 5 7 9,那么5,7和9的表就会出现。它还必须满足诸如MultiplicationTable 7-11这样的输入,它将显示从7到11之间的表。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MultiplicationTable{
static void multTable(int n){
for(int i=0; i<=12; i++){
System.out.printf("%2s", i);
System.out.println(" * " + n + " = " + i*n);
}
}
static String REGEX = "-";
public static void main (String[] args){
Pattern p = Pattern.compile(REGEX);
if(args.length == 0)
System.out.println("Error! No multiplication table entered!");
else{
for(int i=0; i<args.length; i++){
Matcher m = p.matcher(args[i]);
if(m.lookingAt()){ // If a dash is found
int start = Integer.parseInt(args[i].substring(0, m.start()-1));
int end = Integer.parseInt(args[i].substring(m.start()+1, args[i].length()-1));
System.out.println(start + "," + end);
/*for(int j=start; j<=end; j++)
multTable(j);
}
else{
multTable(args[i].Integer.parseInt(substr(0, args[i].length-1)));*/
}
}
}
}
}
问题是程序没有进入这个if语句:
if(m.lookingAt()){
System.out.println(start + "," + end);
是作为一个测试添加的,当执行命令MultiplicationTable 7-11时,不会显示这些值。我是不了解lookingAt()的工作方式,还是我使用它不正确?
发布于 2016-10-13 19:45:16
在您的情况下,lookingAt()
将无法工作,因为该方法只与文本开头的正则表达式匹配。
简单地说,字符串应该以regex模式开始。
有代码的插图-
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String str1 = "7-11";
String str2 = "-11";
String regex = "-";
Pattern p = Pattern.compile(regex);
Matcher m1 = p.matcher(str1);
Matcher m2 = p.matcher(str2);
System.out.println("Does str1 matches with regex using lookingAt method " + m1.lookingAt());
System.out.println("Does str2 matches with regex using lookingAt method " + m2.lookingAt());
}
}
输出 -
Does str1 matches with regex using lookingAt method false
Does str2 matches with regex using lookingAt method true
因此,对于您的问题,您可以使用find()
方法搜索传递给匹配器的文本中正则表达式的出现情况,如果在文本中可以找到多个匹配项,则find()
方法将找到第一个匹配项,然后对于随后对find()
的每个调用,它将移动到下一个匹配项。
您可以将if条件更改为if(m.find())
。单击这里查看工作代码。
如果可以使用除regex以外的任何其他方式,那么您可以通过-
拆分字符串,它将返回字符串数组。
例如
public static void main (String[] args){
String str = "7-11";
String[] stringArray = str.split("-");
System.out.println(stringArray[0]); // 7
System.out.println(stringArray[1]); // 11
}
https://stackoverflow.com/questions/40028738
复制相似问题