Error: not a statement when declaring a boolean in Java - java

The following code:
boolean continue = false;
Returns the following error:
error: not a statement
boolean continue = false;
^
Why is this happening? I am pretty familiar with booleans.

Try this instead:
boolean cont = false;
Or use another name. The point is that in Java, continue is a keyword and it can't be used as a variable name - it's right here in the language specification. For future reference this is what continue is used for:
The continue statement skips the current iteration of a for, while, or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.

You can't use continue as a name of a variable. It's one of java reserved words.

You cannot use continue as a variable name because it is a reserved word.
From the docs:
The continue statement skips the current iteration of a for, while, or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.
You can tell that it is a keyword because, when you look at your question, continue has syntax highlighting applied, like boolean and false.
boolean continue = false;
That would be like writing
boolean boolean = false;
or
boolean false = false;
Both of those obviously won't work, so try something else like continuing:
boolean continuing = false;

Related

JAVA in android studio The value true assigned is never used

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.

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.

Do While Loop Error, Stuck in while loop

I have a boolean Guess function:
public boolean guess() {
String checkInput = scanner.nextLine();
try {
guess = Integer.parseInt(checkInput);
} catch (NumberFormatException e) {
return false;
}
return true;
}
which is called by another function in a do while loop:
while (!player.guess()) {
player.guess();
}
If I enter an int, the program runs properly and terminates. But if input is a non-int character, the program gets stuck in the while loop. I don't know what's going on here.
Your guess function is designed that way.
It returns false if the input is not numeric (catch). So it stays in the loop until you input a numeric value.
Another problem is that you are calling the function twice every loop (once on the loop condition check and another inside the loop). So if you type a non numeric character on the first (loop condition) and a numeric on the second (inside the loop) it will still ask for an input a third time.
I don't know what your intention is but you probably would want something like:
while (!player.guess()) {
continue;
}
Unless you really want it to be called twice.
Your scanner.nextLine() reads the line forever, it doesn't ask for another input.
while (!player.guess()) { // Entered Integer. (!true) and loop breaks
player.guess();
}
while (!player.guess()) { // Entered Non-Integer. (!false) and program enters the loop
player.guess(); // You are not storing the result in some boolean variable
//Therefore, it doesn't matter whether true or false
//while (!player.guess()) will be checked once again
}
SOLUTION:
boolean flag = player.guess(); // capture the result
while (!flag) { // verify the result
flag = player.guess(); // capture the result again
}

How can I 'break out' of a while loop but still do the while loop?

I would like to have a while loop that if a certain condition is true, do not do the code below it and then continue with the while loop.
Here is some psuedocode:
boolean poop
while (poop){
if (player.isAwesome()){
Continue doing while loop but do not execute below code
}
poop = false;
}
Yes, I can use something like this:
boolean poop
while (poop){
boolean stopPoop = false;
if (player.isAwesome()){
stopPoop = true;
}
if (!stopPoop){
poop = false;
}
}
However, that is sort of messy and inconvenient, and I was wondering if there is a better way?
boolean poop = true;
while (poop){
if (player.isAwesome()){
//Continue doing while loop but do not execute below code
continue;
}
poop = false;
}
Yes, that's right use the continue keyword. If you wanted to break out of the loop you could use the break keyword
If you have nest loops then you can also continue to a label.
I don't see the need for the poop variable.
can't you just use this.
while (player.isAwesome()){
Continue doing while loop but do not execute below code
}
In cases such as these where it is difficult to predict when a loop should be terminated, I prefer to use
do {
if (player.isAwesome()){
//Continue doing while loop but do not execute below code
continue;
}
// This code will only execute once
} while (false);
This removes the need for the boolean flag which pollutes the scope outside the loop.
I discourage for (;;) or while (true) since, over time, maintenance of code written in this way can introduce infinite looping.
I assume you are using java for coding.
All you need to do is write
continue;
at the line you need to go to the while loop check statement. So:
boolean poop
while (poop){
if (player.isAwesome()){
continue;
}
poop = false;
}

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