简体   繁体   中英

I keep getting a missing return statement?

In my code I'm trying to go through the arraylist and see if theres any reoccurring numbers. I keep getting an error saying i have a missing return statement. Is my code correct and how do I fix this problem.

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(3);
    list.add(2);
    list.add(7);
    list.add(2);

    System.out.println("Type a number: ");
    int number = Integer.parseInt(in.nextLine());
    if (moreThanOnce(list,number)) {
        System.out.println(number + " appears more than once");
    }
    else 
        System.out.println(number + " number does not appear more than once");
}
public static  boolean moreThanOnce(ArrayList<Integer> list , int number) {
    int count = 0;
    for (int i = 1; i < list.size(); i ++ ) {
        if (list.get(i) == number) {
            count ++;
            if (count > 1) {
                return true;
            }
            else 
                return false;





}

}

只需删除else部分并将“ return false”移到moreThanOnce方法的for循环外即可。

public static  boolean moreThanOnce(ArrayList<Integer> list , int number) {
    int count = 0;
    for (int i = 1; i < list.size(); i ++ ) {
        if (list.get(i) == number) {
            count ++;
            if (count > 1) {
                return true;
            }
            else //delete this line
                return false; // delete this line
        }
    }
    return false;//add return here
}

To solve the error, it only needs a return outside the for loop. And I think you should delete else logic, that makes the method cannot find the number which appears more than one time correctly.

Change to:

public static  boolean moreThanOnce(ArrayList<Integer> list , int number) {
    int count = 0;
    for (int i = 1; i < list.size(); i ++ ) {
        if (list.get(i) == number) {
            count ++;
            if (count > 1) {
                return true;
            }
        }
    }
    return false;
}

This guarantees that a return statement (false) is sent back if either there is not a recurring number that's equal to number and if it never enters the for-loop as well. It will return true if the conditions you put is met.

如果在moreThanOnce方法中未执行for循环,则会丢失return语句。

You're missing a closing brace "}" for moreThanOnce(). It has four open braces, but only three closing braces.

Most code-oriented editors will match braces for you, and help track down imbalanced braces (and parens, etc.) Figure out how to do that in your editor, as that's something you'll need throughout your programming career.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM