Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在返回变量之前检查数组中的所有位置_Java_Arrays_String_Throws - Fatal编程技术网

Java 在返回变量之前检查数组中的所有位置

Java 在返回变量之前检查数组中的所有位置,java,arrays,string,throws,Java,Arrays,String,Throws,我有一个方法,如果在我的菜单数组中按名称找到,它将返回一个Recipe对象。如果找不到它,它会抛出一个自定义RecipeNotFoundException,并只说找不到它 public static Recipe getRecipe(String recipeName){ try{ for(int j = 0 ; j < Menu.length ; j++){ if(Menu[j].getName().equals(recipeName

我有一个方法,如果在我的菜单数组中按名称找到,它将返回一个Recipe对象。如果找不到它,它会抛出一个自定义RecipeNotFoundException,并只说找不到它

public static Recipe getRecipe(String recipeName){

    try{

        for(int j = 0 ; j < Menu.length ; j++){

            if(Menu[j].getName().equals(recipeName)){

                return (Recipe)Menu[j];

            }

            else{

                throw new RecipeNotFoundException();

            }
        }

}catch(RecipeNotFoundException e){

    System.out.println("Recipe Not Found!");

}   

    return null;

}
公共静态配方getRecipe(字符串recipeName){
试一试{
对于(int j=0;j

在当前条件下,它只检查第一个菜单点,如何让它在抛出异常之前检查所有菜单点!?我曾经尝试过反转和翻牌,但这只会导致NullPointerException,并检查整个过程,而无法进行投掷。有人得到一些指导吗?提前谢谢

在整个循环完成后引发异常:

for (int j = 0; j < Menu.length; j++) {
    if (Menu[j].getName().equals(recipeName)) {
        return (Recipe) Menu[j];
    }
}
throw new RecipeNotFoundException();
for(int j=0;j
如果它找到一个配方,它将在到达抛出异常的行之前返回


当然,在这里抛出异常有点毫无意义。如果您不做任何其他事情,您可以在循环之后添加错误处理代码,而不是抛出异常,因为它只是在同一个方法中捕获的。当您希望错误由方法的调用方而不是方法本身处理时,通常会抛出异常。

我甚至不知道您可以这样做!哦,哇,我觉得自己很笨,非常感谢你!