Missing return} statement in java error

I really can’t understand why my code is causing this error, everything looks right, I thought that it continues to appear because there is no return statement}

I tried looking for solutions, and I saw that the “while” after the “if” is one solution, but since I need several numbers that I cannot use at the time, and you need to go with “what if”

Can anyone help me out?

import java.util.*; class WS8Q4 { public static void main (String[] args) { Scanner in = new Scanner(System.in); int x = 0; System.out.println("Please put in an integer from 0 - 9"); x = in.nextInt (); String answer = numTxt (x); System.out.println(answer); } public static String numTxt (int x) { if (x==0) { return ("Zero"); } else if (x==1) { return ("One"); } else if (x==2) { return ("Two"); } else if (x==3) { return ("Three"); } else if (x==4) { return ("Four"); } else if (x==5) { return ("Five"); } else if (x==6) { return ("Six"); } else if (x==7) { return ("Seven"); } else if (x==8) { return ("Eight"); } else if (x==9) { return ("Nine"); } } } 
-4
java return
source share
6 answers

What if x is something other than 0-9? You do not have a return statement for this case. Add it below, below your last else if :

 return "Other"; 
+5
source share

You should have a default return statement.

What to do if the condition is not met? add else to the end.

 else{ return "not found"; } 

And you must write

 return "Zero"; 

No need to write return ("Zero");

And your case is perfect for switch case if you use> 1.6

+1
source share

You need a return at the end of the public static String numTxt() method, otherwise what happens if none of your if blocks satisfies?

0
source share

Add else with the return statement. If x is not 0-9, then it does not fall into any of these return statements. This is what causes the problem.

0
source share

You do not have a return at the end of the function. All of your return are within if branches; the compiler cannot be sure that any of them will ever suffer. You either need return at the very end, or one inside the else branch.

0
source share

You have to take care of all the cases, namely: all the other cases that you described in the if-else chain. To fix this, I would choose an exception, indicating that a digit is not possible:

 public static String numTxt (int x) { String txt[] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; if (0 <= x && x <= 9) return txt[x]; throw new IllegalArgumentException("Unsupported digit!"); } 
0
source share

All Articles