JAVA in android studio The value true assigned is never used - java

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.

Related

Java loop in a method asks for extra return statement [duplicate]

This question already has answers here:
This method must return a result of type boolean(Java)
(3 answers)
Closed 5 years ago.
I am trying to write a method that contains a for loop that loops through a string from the second digit to the end digit, checking to make sure that the characters in that part of the string are all digits.
public static boolean hasValidDigits (String nameAccount)
{
for (int i = 1; i < nameAccount.length(); i++)
{
if(Character.isDigit(nameAccount.charAt(i)))
{
return true;
}
else
{
return false;
}
}
(It keeps asking for an extra return statement here, I have no idea why)
}
I'm expecting the loop to run through the last 5 characters of a 6 character string check to make sure that they are digits and return true if they are, otherwise return false.
My problem is that the code keeps asking for an extra return statement that shouldn't be needed, also as far as results go when I add the extra return statement (just to get the code working) the boolean seems to work for only the starting digit in the string (changing the digit to another character returns false) but if I change any of the other digits further along the string it still returns true even though it should output false.
Any help on this or a push in the right direction would be a great help.
Consider rewriting the method so that there is only one return statement. In this case it's not difficult to debug but if you had 30 execution paths as Matheus mentioned, it could be pretty tricky. You could also consider using regex here. As your code currently is, not all digits will be checked.
You can try regex at https://regex101.com/
at that point your method body could be something like
return yourString.matches(".\\d{5}");
Your method actually behaves as expected. What a return statement does is to terminate a method immediately. What's happening is: your method is not being run completely, it's being terminated prematurely. Try and follow the flow of your method; immediately after the first iteration, the entire method is terminated (with the return statement); so it never actually checks for the remaining characters. A better approach would be to do this:
public static boolean hasValidDigits(String nameAccount){
for(int i = 0; i < nameAccount.length(); i++){
if(!(Character.isDigit(nameAccount.charAt(i)))){
return false;
}
}
return true;
}
This way, when looping, immediately the program encounters a character that is not a digit, the entire method is aborted and it returns false. However if no non-digit is detected, it means the String contains all digits and therefore, it returns true.
It's actually logical:
Check for non-digits...
immediately one is detected, abort and return false...
If the iteration is complete and there is still no non-digit, return true!
I hope this helps!
Merry coding!!!
Your method needs an extra return statement to cover all possible paths of execution. Let's say your user inputs an empty string as its username. Your loop body would not be executed.
That's the reason Java is requiring an extra return statement.

how to pass a variable through sendKeys in selenium webdriver?

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.

java singleton boolean expression to return message instead of true or false

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.

How to check if there are double letters in a 4 digit code in Java

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

Java error: missing return statement?

Here is my method:
//usedLetters method to check if user's guess has already been guessed
private boolean usedLetters(char used[], char alphabet) throws IOException
{
for(int x=0; x<used.length; x++){
if(alphabet == used[x])
{
return true;
}
else
{
used[dataSize] = alphabet;
return false;
}
}
}//End of usedLetters method
IT checks to see if the alphabet that the user entered in an another method has already been guessed. If it has already been guessed, it returns true, and if has not been already guessed, it adds the alphabet into used, and returns false. But the error says that there are no return statements...I am not familiar with methods in general, so I am confused. Any help would be appreciated!
What if used.length==0? Then the for-loop is never entered.
Therefore you need a return statement after the loop.
What if the for is never entered? i.e. used.length == 0 (used is an empty array). In this case - nothing will be returned.
The compiler forbids a flow that can terminate without returning the value, and that's why it shows the error.
Also note, I believe even after fixing this issue - the program will yield a wrong result, it will only check the first element of used, without advancing to the next one.
You should move the return false; to just before the last }. Otherwise it will return in the first iteration of the loop.
/usedLetters method to check if user's guess has already been guessed
private boolean usedLetters(char used[], char alphabet) throws IOException
{
for(int x=0; x
if(alphabet == used[x])
{
return true;
}
else
{
used[dataSize] = alphabet;
return false;
}
}
}//End of usedLetters method
There should be return statement after for loop, currently there is no return statement that's why you are getting error.
As you have written your code, the method will always return on the first iteration of the cycle, while I doubt this is what you want.
I believe that you should return false outside the for. I am not sure what does to "guess an alphabet" mean but I think this is what you are trying to do.
Yep, all the above are correct. You would be better off defining the return variable at the top, setting it to values wherever you need to within the method body, breaking out of the 'for' loop and returning it once at the end.

Categories

Resources