Java program that uses split to validate input. Simplifying but keeping things Fuctional
Any help would be greatly appreciated.
I am not trying to list the operators (I know it will work that way). I want to know if I can put them in a package as I tried in my code below (it didn't work, does anyone know why? How to fix this?):}
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[2]);
double answer;
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
String operator = token[1];//this is the operator
if (operator.equals(function)){
for (int i = 0; i<length; i++) {
}
System.out.println("Operation is " + token[1] + ", numbers are " + token[0] + " and " + token[2]);
}
else {
System.out.println("Your entry of "+ input + " is invalid");
}
}
0
source to share
3 answers
first you have to split. You cannot access token[0]
before declare
tokens
String function = "[+\\-*/]+"; //this
String[] token = input.split(function );//and this
then use the array [index]
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[2]);
change ....
you have to use. matches
instead. equals
because .equals is looking for a whole string, not a regex
full code
Scanner scan = new Scanner(System.in);
System.out.println("enter your operation");
String input = scan.next();
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[1]);
double answer;
String operator = input.toCharArray()[token[0].length()]+"";
if (operator.matches(function) && (token[0]+token[1]+operator).length()==input.length()) {
System.out.println("Operation is " + operator+ ", numbers are " + token[0] + " and " + token[1]);
} else {
System.out.println("Your entry of " + input + " is invalid");
}
exit →
for input "2+3" > Operation is +, numbers are 2 and 3
for input "24+45" > Operation is +, numbers are 24 and 45
for input "2++4" > Your entry of 2++4 is invalid
0
source to share
the code could be like this:
double answer;
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[1]);
String operator = input.substring(token[0].length,token[0].length+1)//this is the operator
if (token.length > 1){
System.out.println("Operation is " + token[1] + ", numbers are " + token[0] + " and " + token[2]);
}
else {
System.out.println("Your entry of "+ input + " is invalid");
}
}
0
source to share