我正在用java创建一个分数类。程序采用整个分数表达式,并使用 switch 语句基于运算符执行操作。除了程序被赋予减法表达式(即 -1/2--1/2(外,我什么都行。当我测试此表达式时,我收到数字格式异常。我相信这与我的字符串标记器中的分隔符有关,但不确定该怎么做。任何帮助,不胜感激。
String regex = "-?[0-9]+[ t]*/[ t]*-?[0-9]+[ t]*[+-/\*][ t]*-?[0-9]+[ t]*/[ t]*-?[0-9]+";
Scanner input = new Scanner(System.in);
System.out.print("Please enter a fraction expression i.e., -1/2 - -1/4: ");
String expression = input.nextLine();
if (!expression.matches(regex)) {
System.out.println("Not a valid fraction expression");
}
ArrayList<String> myList = new ArrayList<>();
StringTokenizer st = new StringTokenizer(expression, "-/*t ", true);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (!token.equals(" ") && !token.equals("t"))
myList.add(token);
}
int num1 = Integer.parseInt(myList.get(0));
int den1 = Integer.parseInt(myList.get(2));
int num2 = Integer.parseInt(myList.get(4));
int den2 = Integer.parseInt(myList.get(6));
Fraction fraction1 = new Fraction(num1, den1);
Fraction fraction2 = new Fraction(num2, den2);
String operator = myList.get(3);
switch (operator) {
case "+":
System.out.println(fraction1.add(fraction2));
break;
case "-":
System.out.println(fraction1.sub(fraction2));
break;
case "*":
System.out.println(fraction1.mult(fraction2));
break;
case "/":
System.out.println(fraction1.div(fraction2));
break;
}
我测试了您的代码片段,并在更改分隔符时使其工作 "-/\t " 自 "/\t ">
另一方面:当键入的字符串与您的表达式不匹配时,您可能希望返回代码:
if (!expression.matches(regex)) {
System.out.println("Not a valid fraction expression");
return;
}