问题
I want to pass the float variable 'f' through sendKeys in the below program.Can someone please let me know the same? As of now, it is throwing
"The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments ".
Code:
public static String isEditable(String s1) {
f=Float.parseFloat(s1);
System.out.println(f);
boolean bool=webDriver.findElement(By.xpath("expression")).isEnabled();
if(bool) {
if((f<0) || (f>6)) {
error="Value must be between 0.00% and 6.00%";
System.out.println(error);
} else {
webDriver.findElement(By.xpath(""expression")).sendKeys(f);
}
} else {
error="Please enter a valid Number";
}
return error;
}
回答1:
Convert the float to a string:
webDriver.findElement(By.xpath("...")).sendKeys(Float.toString(f));
回答2:
I know you already accepted an answer but I wanted to clean up your code a little and give you some feedback.
I changed the name of the function because a function named
isEditable()
should return aboolean
indicating whether some field is editable. That's not what your function is doing so it should be given a more appropriate name. I made a guess at what the actual name should be... I could be way off but you should name it something more along the lines of what it's actually doing... putting text in a field.I removed the
isEnabled()
check because that should be done in the function that sets the fund number. Each function should do one thing and only one thing. This function validates that the rate passed is in a valid range and then puts it in the field.I removed the duplicate code that was scraping the INPUT twice. Just do it once, save it in a variable, and reuse that variable. In this case, there's no need to scrape it twice.
and as d0x said, you shouldn't convert the
s1
string to afloat
and then back tostring
when yousendKeys()
... just send thes1
string. Translating it back doesn't help readability, it just means you wrote more code that someone after you will need to understand. Favor clean code... it's always more readable.public static String enterRate(String s1) { f = Float.parseFloat(s1); WebElement input = webDriver.findElement(By.xpath(".//*[@id='p_InvestmentSelection_4113']/div/div/div[5]/div/ul/li/div[3]/div[2]/label/div[1]/input")); if ((f < 0) || (f > 6)) { error = "Value must be between 0.00% and 6.00%"; } else { input.sendKeys(s1); } return error; }
回答3:
Can you try passing s1
instead of f
. Because the method takes a string, not a float.
Your method should look like this:
String selector = "expression";
webDriver.findElement(By.xpath(selector)).sendKeys(f);
And please use better variable names like userInput
instead of s1
or userInputAsFloat
instead of f
or investmentInputVisible
instead of bool
etc.
来源:https://stackoverflow.com/questions/33563054/how-to-pass-a-variable-through-sendkeys-in-selenium-webdriver