Java error: missing return statement? - java

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.

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.

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
}

Validation is working too well

I have this validation to check that user input is not blank and is only letters. If it's blank, it catches it, and if if includes digits it also catches it. If I input the 2 characters it asks for, however, it doesn't go through. I'm not sure how to go about this.
private static boolean isValidSt(String aSt) {
boolean result = false;
try {
if (aSt.length() == 2) {
result = true;
} else if (aSt.length() != 2) {
result = false;
}
for (int i=0; i <aSt.length();){
if (!Character.isLetter(i));{
return false;
}
}
return true;
} catch (NumberFormatException nfex) {
if (aSt == null) System.exit(0);
} catch (Exception ex) {
if (aSt == null) System.exit(0);
}
return result;
}
One problem that I can see right of the bat is this:
if (!Character.isLetter(i));{
return false;
}
That semi-colon after your if does not belong there. After checking your conditional statement, if it was true, it will execute until the semi-colon. The return false; isn't part of the if and will ALWAYS be executed.
As David Wallice rightly pointed out, you also never increment the counter in your for-loop, so were it not the case that the program always returned with false in the first iteration, it would indeed get stuck in an eternal loop. A very commonly used syntax for for-loops would be:
for(int i = 0; i < string.length(); i++) { }
A third and final note from me, this time nothin that would give an error, just good form:
You use System.exit(0); to exit the program as result of an exception. The zero you pass as an argument is usually only used when the program shuts down normally. This is a crash as a result of an error, so I'd use 1 or something.
Well, you could use StringUtils methods, isBlank and isAlpha, for validate what you need

Am I not returning a string? [duplicate]

This question already has answers here:
"Missing return statement" within if / for / while
(7 answers)
Closed 8 years ago.
I'm writing a method to find the upper case letters in a given string. I have this
public static String FindUpperCase (String x){
for (int i = x.length(); i>=0; i--){
if (Character.isUpperCase(x.charAt(i))){
return x.substring(i); }
}
But I'm getting an error thats telling me I must return a string. When I look up on the API what substring does it tells me that it returns a string that is a subset of the other string...which means I am returning a string, right? I was told that it was because I am returning a string within the loop and that's not the same thing but I'm a little confused by what this means because isn't the loop in the method? Does anyone know what I'm doing wrong or how I can fix this?
No, you're not always returning a string. What if the input is entirely lower case?
Basically, you need a return statement (or throw an exception) after the for loop, to handle the situation where you get to the end of it. Even in cases that you can reason that you'll never actually get to the end of the loop, the Java compiler follows strict rules for reachability, as specified in section 14.21 of the JLS. So even if your return statement were unconditional and we know that length() always returns a non-negative value, this still wouldn't compile:
public static String broken(String input) {
// *We* know that we'll always go into the body of the loop...
for (int x = input.length(); x >= 0; x--) {
return input;
}
// The end of the method is still reachable from the compiler's standpoint
}
The end of a non-void method can't be reachable - you must either throw an exception or return a value.
Also note that your initial value should be x.length() - 1 or x.charAt(i) will throw an exception. You should also change your method name to follow Java naming conventions.
Oh, and currently you're not returning "the upper case letters" - you're returning "everything from the last upper case character onwards" which is entirely different.
You are returning subjected to a condition, so if the condition is never true you are not returning. Try instead.
public static String FindUpperCase (String x){
for (int i = x.length() - 1; i>=0; i--){
if (Character.isUpperCase(x.charAt(i))){
return x.substring(i); }
return "";
}
Also Java is indexes start at 0, so your for sentence starts at x.length() - 1 (last position) or you will get StringIndexOutOfBoundsException
Consider the case when there's no uppercase in the given string, in that case, the function won't return anything.
So just after your for loop, you can return an empty string to make the function declaration valid.
Because you return string only if Character.isUpperCase(x.charAt(i)) is true. You have to return for example empty string if it is false.
public static String FindUpperCase (String x){
for (int i = x.length(); i>=0; i--){
if (Character.isUpperCase(x.charAt(i))){
return x.substring(i); }
}
return "";
}
Your problem is, that you are returning a string dependend on an if statement. You have to return a string or null in every possible case. Just place a return null or return "" at the last line of the function for a quick and dirty solution. Better would be to think what you want to return if no uppercase character is found.

Java - changing a method to a for/while loop

I want to change the first method to a while and for loop. I have added the code below. Is this correct?
public String extractWordFour(String text){
if(text.length()==0 || text.charAt(0) == ''){
return "";
} else {
return text.charAt(0) + extractWordFour(text.substring(1));
}
}
public String extractWordFour(String text){
int i=0;
while (i<=text.length){
return text.charAt(0) + extractWordFour(text.substring(i));
i++;
}
}
public String extractWordFour(String text){
for(int i=0;i<=text.length();i++){
return text.charAt(0) + text.substring(1);
}
}
I'm not going to answer this question because I think its a h.w. assignment but I'm putting it in an answer since I can't fit this in a comment, but I'm assuming you want to convert a recursive solution into a while or for loop solution.
Your while solution is wrong first of all because you are mixing recursion and while together. You should not be calling the function inside your while loop!
public String extractWordFour(String text){
int i=0;
while (i<=text.length){
return text.charAt(0) + extractWordFour(text.substring(i));
i++;
}
}
This one can't finish because you are returning it before its even looped more than once.
public String extractWordFour(String text){
for(int i=0;i<=text.length();i++){
return text.charAt(0) + text.substring(1);
}
}
Anyways hope that helps. The best thing to do would be to fully understand what the first function does, write it down and then think about how to make it do the exact same thing with a while or a for loop.
For a start, you can't have String.charAt(0) == '' because '' isn't a valid character, unlike "" for an empty String which is valid.
Your second method doesn't work because it should be text.length() instead of text.length which is the method when you're calling it on an array, as well as the i++ being unreachable because of the recursion. And failing that, the method signature claims it returns a String, but there is no return statement.
Your third method does have a return statement, but it still wouldn't work because it'll just return on the first iteration and therefore only give you the first 2 characters (and in fact your compiler won't even allow it because it won't realise this).
Aside from all these issues, if the method name of extractWordFour is an accurate representation of what they should do, none of them will because the logic makes no sense. I suggest you start by thinking about that: How can you tell when one word ends by examining the String, and what does your program need to know to remove everything before the fourth word, and everything after it?

Categories

Resources