检查某些代码时出错

时间:2016-03-27 21:43:22

标签: java

我做错了解释。现在我做了更好的解释。我的问题是错误处理,这不是例外。所以我的代码如下。如果我不想输入非正整数(例如

),我可以检查机智试试吗?
import java.util.Scanner;

public static void main(String[] args) {
    System.out.println("Type in the expression with no empty spaces: ");

    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();

    String[] tokens = split("[*,/,+,-");  

    for (int i = 0; i < 1; i++) {
        String delims = tokens[1];

        double n1 = Double.parseDouble(tokens[0]); 
        double n2 = Double.parseDouble(tokens[2]);

        switch(tokens) case1;"+"  System.out.println(n1+n2) // All cases
    }                       
}

1 个答案:

答案 0 :(得分:0)

您可以使用Regex检查表达式是否有效。 String类提供matches()方法来验证带有Regex的字符串,例如:

String regex = "[0-9]+[-+/\\*][0-9]+";
String expression = "3+6"; 
System.out.println("3+6".matches(regex));

您可以在matches条件中使用if来验证用户的输入。完成后,您可以使用&#39; split(&#34; \ b&#34;)&#39;提取操作数和运算符。

<强>更新

添加上述逻辑后的代码如下所示:

Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String regex = "[0-9]+[-+/\\*][0-9]+";
if(s.matches(regex)){
    String[] tokens = s.split("\\b");
    //Your logic
}else{
    System.err.println("Please try in a valid expression!");
}