Java Program Using Split to Validate Input. Simpli

2019-08-27 09:20发布

问题:

Any help would be appreciated.

I am not trying to list the operators, ( I know that it would work that way) i want to know if i can put them in a bundle as i attempted in my code below (it did not work, anyone knows why? how to fix it?): }

        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");
        }


        }   

回答1:

first you should split .you can't access token[0] before declare tokens

String function = "[+\\-*/]+"; //this
String[] token = input.split(function );//and this

then use array[index]

double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[2]);

edit....

you should use .matches instead .equals because .equals looking for entire String not regular expression

complete 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");
}

output>>

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


回答2:

the code may 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");
}
} 


回答3:

Access token after splitting input

double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[2]);

And

String operator = token[1];//this is the operator

wont work because delimiter wont be there in the String array after splitting.