编译错误:缺少返回语句

Compiling Error: Missing return statement(编译错误:缺少返回语句)

本文介绍了编译错误:缺少返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个程序用 3 种不同的方法玩掷骰子.我在玩掷骰子时需要帮助,但我需要使用这 3 种不同的方法,但由于某种原因,每次编译时都会出现此错误:

This program plays craps with 3 different methods. I need help in playing craps but i'm required to have these 3 different methods but for some reason every time I compile I am getting this error:

CrapsAnalysis.java:48: error: missing return statement
    }
    ^
1 error
Process javac exited with code 1

代码:

public class CrapsAnalysis
{   
public static int rollDie( int n) {
    return (int)(Math.random()*n) + 1 ;
}
public static int rollDice( ) {
    return rollDie(6) + rollDie(6) ;
}
public static boolean playOneGame( ) {
    int newDice = rollDice();
    int roll = rollDice(); //first roll of the dice
    int playerPoint = 0; //player point if no win or loss on first roll
    if (roll == 7 || roll == 11)
        return true;
    else if (roll == 2 || roll == 3 || roll == 12)
        return false;
    else    
        playerPoint = roll;
    do {
        if (rollDice() == 7)
            return false;
        else if (rollDice() == playerPoint) 
            return true;
        else
            newDice = rollDice();
        } while (rollDice() != playerPoint || rollDice() != 7) ;
    }
}

推荐答案

Java 必须查看所有执行路径.如果 while 循环结束而不返回任何内容会发生什么?您可能在逻辑上阻止了这一点,但 Java 编译器不会进行这种分析.

Java must look at all execution paths. What happens if the while loop ends without returning anything? You may be logically preventing that, but the Java compiler won't do that analysis.

while 循环结束后提供 return 语句,或抛出某种 Exception (IllegalStateException?)如果代码真的不应该在那里.

Provide a return statement after the end of the while loop, or throw some kind of an Exception (IllegalStateException?) if the code really shouldn't ever make it there.

这篇关于编译错误:缺少返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:编译错误:缺少返回语句

基础教程推荐