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;
}
Convert the float to a string:
webDriver.findElement(By.xpath("...")).sendKeys(Float.toString(f));
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 a boolean 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 a float and then back to string when you sendKeys() ... just send the s1 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;
}
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.
Related
I wrote A method to check that the password A user enters when registering to the app is valid.
A valid password will be with length of 8-16 charachters and contains only numbers,uppercase and lowercase letters.
according to android studio in the For loop when the value is OK it will never assign the value true to the variables and I can't understand why.
Is it becuase I am trying to work directly with EditText or am I just doing it wrong?
This is the method:
boolean PasswordTest(EditText password){//function to check that the password is OK
boolean upLetter=false,lowLetter=false,digit=false;
int i;
if(password.length()<8||password.length()>16){
Toast.makeText(getApplicationContext(),"Password must be between 8-16 characters",Toast.LENGTH_LONG).show();
return false;
}
for(i=0;i<password.getText().length();i++) {
if (Character.isDigit(password.getText().charAt(i))) {
digit = true; //The value true assigned to digit is never used
} else if (Character.isUpperCase(password.getText().charAt(i))) {
upLetter = true; //The value true assigned to upLetter is never used
} else if (Character.isLowerCase(password.getText().charAt(i))) {
lowLetter = true; //The value true assigned to lowLetter is never used
} else {
Toast.makeText(getApplicationContext(),"Password must contain uppercase,lowercase and numbers",Toast.LENGTH_LONG).show();
return false;
}
}
Toast.makeText(getApplicationContext(),"all data is correct",Toast.LENGTH_LONG).show();
return true;
}
thanks for the help
according to android studio in the For loop when the value is OK it will never assign the value true to the variables and I can't understand why.
You misread the warning.
Your code is assigning values to these 3 local variables (or well, it should do that, depending on the input data).
But then the method ends, and these 3 local variables cease to exist.
The warning tells you that these assignments are meaningless because there is no other code following that uses the 3 local variables for anything.
In other words: you have to step back and ask yourself: "okay, now that the loop is over, how should I use these 3 local variables to do something else".
So: this has nothing to do with the editor you are using. The tool tells you that the code you have written "makes no sense". When you do not use the result of an operation, then why compute it?!
You could switch this over to regex and make it simple.
Pattern pattern;
Matcher matcher;
final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$";
boolean PasswordTest(EditText password){//function to check that the password is OK
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
And then on the method calling the PasswordTest check and then show a Toast message.
I am working on a program that allows me to move a pen, making a mark on a canvas. At the moment, I have a method called convertToInteger in class "MyInput" (which in the class with my methods I've referred to as "reader"), which converts a string into an integer.
public int convertToInteger(String word)
{
return Integer.parseInt(word);
}
I've then tied this into my method, converting a string input into an integer.
case "move":
int distance = reader.convertToInteger(command.get(1));
brush.move(distance);
break;
Thus, in my program I can type "move 100" and the brush move 100 pixels. The code, in its current state, crashes with an exception error if I tried typing a non-integer; e.g. "move here".
In "MyInput" class, I created a boolean method that checks to see if it's a integer or not using 'try' and 'catch':
public boolean isAnInteger(String word)
{
boolean ok;
try {
Integer.parseInt(word);
ok = true;
}
catch(NumberFormatException ex) {
// Non-integer string.
ok = false;
}
return ok;
}
Then tried implementing it in my code:
case "move":
int distance = reader.convertToInteger(command.get(1));
if (reader.isAnInteger(command.get(1)) == true){
brush.move(distance);
}
else {
printError();
}
break;
When I run the code and type something like "move here" in the terminal, it throws an exception so clearly its bypassing my code - but typing "move 100" or any other valid integer works.
Any suggestions? Thanks in advance.
Your instructions are in the wrong order. Your are attempting to parse, then checking if it can be parsed. You should really check first, then try to parse.
I am fairly new to Java. Over the past few weeks I have been trying to teach myself java. This has been primarily based on tutorials i find online and forums I can find. So keep this in mind and any additional critique you can share is greatly appreciated! I am currently trying to create a calculator that runs off of if-else loops. I'm working on a method that allows the user to derive a function based on the principle that if
f(x)=ax^n+bx^o+cx^p... then f'(x)=anx^n-1+box^o-1+cpx^p-1...
I'm trying to use .split() to separate the parts of the function, perform the changes to the individual parts, and then print them together. I could get most of the way through this but I couldn't convert a string with a negative sign to an integer so I am trying to call a method that uses .substring and then replaceAll to get rid of the negative sign then convert to integer. However, I keep getting a compiling error stating the "actual and formal argument lists differ in length". Can anyone explain why this might be happening?
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class InputInteger
{
public String changeSign(String second) {
String negative = second.substring(0,1);
return negative;
}
public static void splitFunction() {
Scanner o = new Scanner(System.in);
String function = o.next();
String[] parts = function.split("(?=\\+|\\-)");
for (int i = 0; i < parts.length;) {
String[] second = parts[i].split("(?=[0-9]+|[a-z]+|[A-Z]+\\^)");
InputInteger.changeSign();
if (negative = ("-")) {
second = second.replace("-","");
int x = Integer.parseInt(second[0]);
int y = Integer.parseInt(second[2]);
int w = x*y;
int z = y-1;
System.out.println(w + "x^" + z);
i++;
}
}
}
Problem that you are talking about is the method not working . You have to pass argument in the function like
InputInteger.changeSign(function);
or
InputInteger.changeSign(second[i]);
according to requirement
changeSign(String second) should be defined as static
negative variable is not defined
you should compare strings with equals() method
you call .replace(...) on an array, which doesn't have this method
And these are only compile errors, I see at least one runtime problem:
you increase i only in the if which may result in an infinite
loop...
I suggest you use some good IDE like Eclipse or IntelliJ IDEA, which will help you with warnings/errors/etc.
First of all in your code if (negative = ("-")) you have a single "=" and I think you meant to use "==" for comparison. Second, method parseInt() as well as valueOf() (which I prefer to parseInt()) should handle negative numbers just fine. there is no need to remove "-". Yout method changeSign() takes a String argument, also your method ChangeSign() returns String value and you must assign a result to some String: String negative = InputInteger.changeSign(str);. Plus also String class has a method startsWith(String prefix) that fits your better then substring(). Hope this helps. If anything there is an Open source library that provides a Utility for parsing String into Integer (among other things). in That util there is a method
parseStringToInt(String numStr, int defaultValue,
String nullOrEmptyStringErrorMessage, String numberFormatErrorMessage)
That tries to parse a String to Integer and if it does not succeed it returns a default value and never throws an Exception. That method definitely works fine with negative integers. Here is the link to the article about the library.https://www.linkedin.com/pulse/open-source-java-library-some-useful-utilities-michael-gantman?trk=pulse_spock-articles. There you will find the instructions on where to get the library including javadoc and source code.
How can we get the boolean expression of a basic singleton with hashsets to return a message in lieu of the original 'true' or 'false'?
public boolean bookLane(String lane) {
return runLane.remove(lane);
}
I want to only replace the true or false return statements with a message.
To help clarify this question, something like below (i know it doesn't work) is the direction I am wanting to go...
public boolean bookLane(String lane) {
if (true)
{
message = "Lane is available. Adding runner...";
//instead of true
}
else
{
message = "Lane unavailable. Please choose another";
//instead of false
}
return runLane.remove(lane);
}
I just tried messing with the code and found that it only returns false now.
public boolean bookLane(String lane) {
String message1 = "Lane Available. Adding runner...";
String message2 = "Lane is Unavailable.";
if (runLane.remove(lane))
{
System.out.println(message1);
}
else
{
System.out.println(message2);
}
return runLane.remove(lane);//
}
Any ideas on fixing it? Not gonna lie, my experience with Java is mainly trial and error with a little help from more experienced programmers. I think this method could work if someone could let me know what I am missing as far as how boolean methods work with more than just the one return type. I am trying to target the return value for displaying the appropriate message with the returned boolean. Is this route even possible? Am I missing some logic in how boolean methods work or something? Please understand my frustration and my need for yalls help. thanks for the guidance given...
In these cases it might be useful to define a new data structure, since you want to retrieve two pieces of information from the same method. Consider the following:
class BookLaneResult {
boolean success;
String message;
// add constructors / getters / other stuff you need
}
Then your code becomes this:
public BookLaneResult bookLane(String lane) {
// some logic to determine if lane is available or not
boolean laneAvaiable = ...;
return new BookLaneResult(laneAvailable, laneAvailable ? "Lane available" : "Lane unavailable");
}
If the BookLaneResult is to be used only in that case with only those messages, then you can just use a boolean parameter constructor and set the message based on the argument internally. However, to make the new data structure more flexible you can name it OperationResult and use it whenever you perform some kind of operation and expect to retrieve a boolean flag representing the operation success or failure and the message stating what happened.
Here is what I used for a boolean operation trying to figure out if a character is a letter - if it is a letter, true, false if no.
Code
boolean isLetter = Character.isLetter(ch);
if (isLetter == true) {
Boolean.toString(isLetter);
System.out.println(" This is a letter."); }
else {
Boolean.toString(isLetter);
System.out.println(" This is not a letter."); }
Worked for me - might be able to apply to other boolean operations.
Output
Input data: 123456abcdef
1 2 This is not a letter
2 3 This is not a letter
3 4 This is not a letter
4 5 This is not a letter
5 6 This is not a letter
6 7 This is not a letter
a b This is a letter
b c This is a letter
c d This is a letter
d e This is a letter
e f This is a letter
f g This is a letter
I realize this is years late, but including this for those who pop up on this thread from a Google search.
The above question might seems vague but it's actually a very simple idea which i can't seem to figure out.
It basically is a 4 digit letter code containing letters from A to F for example: ABDF, BAAF, DBAF etc.
Now I'm trying to do some post input-handling where it must become impossible to enter a letter that is already in the code cause it has to be a unique 4 digit code with no repeating letter. I've been trying to make it work but none of my code seems to work so i'm back to scratch asking you guys for help :)
I hope this is somewhat clear otherwise i'll be happy to clear it up.
Thanks in advance.
Kind of a pseudocode but it would work.
String uniquePass="";
while(uniquePass.length<4){
String userInput=getUserInputChar()
if(uniquePass.contains(userInput))
rejectInputAndNotifyUser
else
uniquePass=uniquePass+userInput
}
public static boolean hasDuplicateChars(String string) {
Set<Character> chars = new HashSet<Character>();
for (char c : string.toCharArray()) {
if (!chars.add(c)) return false;
}
return true;
}
Set is a collection that contains no duplicate elements. We will use add method which returns true if this set did not already contain the specified element.
hasDuplicateChars functions iterates over characters in the input string using toCharArray function and for loop; each character is added to the chars set which is initially empty. If add method returns false it means that we have already encountered same character before. So we return false from our function.
Otherwise input is valid and method returns true.
using this function you'll be able to see if the string contains unique characters
public static boolean checkForUnique(String str){
boolean containsUnique = false;
for(char c : str.toCharArray()){
if(str.indexOf(c) == str.lastIndexOf(c)){
containsUnique = true;
} else {
containsUnique = false;
}
}
return containsUnique;
}
Update:
This will be ran everytime a user enters a character and if it fails, this would mean there is a duplicate. You have the choice of discarding that input or showing an error.
If you're validating the complete input, you can lean on the set semantics, and a few tricks
String s = "ABAF";
int count = new HashSet<>(Arrays.asList(s.split(""))).size();
if (count - 1 == 4) {
System.out.println("All ok");
} else {
System.out.println("Repeated letters");
}
the split("") will split the string to a an array like {"","A", "B", "A", "F"}.
The new HashSet<>(Arrays.asList(s.split(""))) will create a Set with String elements, and as the Set will bounce back the elements already contained, the size of the set for e.g. "AAAF" will be 3 (it'll contain the "", "A" and "F"). This way you can use the size of the set to figure out if all letters of a String are unique
If its while typing you'll than the solution depends on the input method, but you can have something like (pseudo stuff)
if (pass.contains(letter)) {
breakAndNotifyUser();
} else {
pass+=letter;
}