-2

I did wrong explanation . Now I am doing better explanation. My problem is error handling that is not exception. So my code is below. Can I check wit try catch if I dont want to enter non-positive integer for example

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
    }                       
}
Nyunus
  • 1
  • 3
  • Possible duplicate of [Validating input using java.util.Scanner](http://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) – Tom Mar 28 '16 at 09:32

1 Answers1

0

You can use Regex to check whether expression is valid or not. String class provides matches() method to validate a string with Regex, e.g.:

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

You can use matches inside an if condition to validate user's input. Once that is done, you can use 'split("\b")' to extract operands and operator.

update

The code after adding above logic will look like this:

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!");
}
Darshan Mehta
  • 27,835
  • 7
  • 53
  • 81