JAVA: missing return statement

不想你离开。 提交于 2019-12-18 09:49:35

问题


my main concern with this code as of right now is a missing return statement.

public class stringstuff{

    //using charAt    
    public static String ReverseF(String n){
        String finalstring = "";
        int len = n.length();
        for (int i = 0; (i < n.length()); i++){
            finalstring += (n.charAt(len - i - 1));
        }
        System.out.println(finalstring);
    }

    public static void main(String[]args){
        ReverseF("Hello");
    }
}

Using this code I only get the error:

stringstuff.java:11: missing return statement
}
^
1 error

If I switch the System.out.println to return, I don't get any errors but I also don't get an answer for ReverseF("Hello");


回答1:


You have two options: either write

public static void /* not String */ ReverseF(String n){

or write return finalString in ReverseF and use

public static void main(String[]args){
  System.out.println(ReverseF("Hello"));
}



回答2:


Let's break down the keywords in your function header:

Public - Any function has access to this function
Static - This function does not operate on object instance variables and does not require an instance of this object to be created before it can be used
String - this function will return a String
..name.. - the name of the function
(params) - input for your function

Now note that Java thinks this function will return a string. The compiler checks to see if there is a return statement of the proper type.

Either use a void as the functio type and print the string inside of the function (as you' re doing now), or add the return statement and move the print to the place where the function is called from (as already suggested).

HTH




回答3:


You get an compilation error "missing return statement" because your return statement is missing...

public class Stringstuff {

    // using charAt
    public static String reverseF(String n) {
        String finalstring = "";
        int len = n.length();
        for (int i = 0; i < n.length(); i++) {
            finalstring += n.charAt(len - i - 1);
        }

        return finalstring;
    }

    public static void main(String[] args) {
        System.out.println(reverseF("Hello"));
    }
}

Is it necessary that your method is returning a value? If not, just change it from String to void, do the printing in your method and rename it to something like "printReverseF", so that your method name indicate what it's doing!

Other feedback:

  • start method names with lowercase, so you can distinct them from Classes
  • for concatenation of Strings in loops, you should use a StringBuilder/StringBuffer. Then Java doesn't have to create new String-objects per iteration of your loop - this could be a huge performance problem!


来源:https://stackoverflow.com/questions/19525594/java-missing-return-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!