'how to get from string two operators and operand in java?
do I need to get two operators and an operand between them from a string in the range 1-10?
public class Main {
public static String calc(String input) {
String [] operands = input.split("[+-/*]");
int op1 = Integer.parseInt(operands[0]);
int op2 = Integer.parseInt(operands[1]);
String [] op = input.split("[0-10]");
return "";
}
public static void main(String[] args) {
calc("19-10");
}
}
Solution 1:[1]
A temporary workaround would be:
public class Main {
public static String calc(String input) {
String [] operands = input.split("[+-/*]");
int op1 = Integer.parseInt(operands[0]);
int op2 = Integer.parseInt(operands[1]);
//op3 is your input value but without the first number
String op3 = input.split(operands[0])[1];
//op4 is your input value without the first and last number
//op4 would be "-" in your case
String op4 = op3.split(operands[1])[0];
return "";
}
public static void main(String[] args) {
calc("19-10");
}
}
A better solution would be:
public class Main {
public static String calc(String input) {
String [] operands = input.split("[+-/*]");
int op1 = Integer.parseInt(operands[0]);
int op2 = Integer.parseInt(operands[1]);
String[] ops = input.split("\\s*[0-9999]+");
//ops[1] will be "-"
return "";
}
public static void main(String[] args) {
calc("19-10");
}
}
Search for "Java Regex example". I can't explain it that easy.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
