Java 需要找出determineast模块中return语句的错误

Java 需要找出determineast模块中return语句的错误,java,Java,我正试图让这段代码正常工作,我的问题在于让return语句正确,这样它就能打印出正确的结果。非常感谢您的帮助。问题在于让它返回正确的值。当我让它工作时,它将返回一个值0 public static void main (String []args){ int famIncome, numChildren, asstTotal, asstAmount; numChildren = userChildren(); famIncome = userIncome();

我正试图让这段代码正常工作,我的问题在于让return语句正确,这样它就能打印出正确的结果。非常感谢您的帮助。问题在于让它返回正确的值。当我让它工作时,它将返回一个值0

public static void main (String []args){

    int famIncome, numChildren, asstTotal, asstAmount;

    numChildren = userChildren();

    famIncome = userIncome();

    asstTotal = determineAsst(numChildren, famIncome);

    System.out.println(asstTotal);
    }

public static int userChildren (){
    int children = 0;
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter Your Number of Children: ");
    children = keyboard.nextInt();

    return children;
}

public static int userIncome (){
    int income = 0;
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter Your Family Income: ");
    income = keyboard.nextInt();

    return income;
}

public static void displayResults(int famIncome, int numChildren){

    System.out.println("Your Income is: " + famIncome + " " + "Children: " + numChildren);

}

public static int determineAsst (int userIncome, int numChildren){


    if(userIncome > 25000 && numChildren > 2){
        int asstTotal = 0;

         asstTotal = numChildren * 1000;

         return asstTotal;

    }


    return asstTotal;


}

}

为了进行编译

public static int determineAsst (int userIncome, int numChildren){
   if(userIncome > 25000 && numChildren > 2){
      int asstTotal = 0;
      asstTotal = numChildren * 1000;
      return asstTotal;
   }
   return asstTotal;
}
必须更改为:

public static int determineAsst (int userIncome, int numChildren){
   int asstTotal = 0;
   if(userIncome > 25000 && numChildren > 2){
      asstTotal = numChildren * 1000;
   }
   return asstTotal;
}
在原始代码中,
asstTotal
变量直到在if块内才会声明。这意味着一旦if块退出,该变量就不再存在。它是错误的,因此,return语句不会编译

另外,正如@donfuxx所提到的,if块中的return语句是不必要的。它可以工作,但它是多余的


这能解决您的问题吗?

重写方法如下:

public static int determineAsst (int userIncome, int numChildren){

    int asstTotal = 0; //here!
    if(userIncome > 25000 && numChildren > 2){
        //int asstTotal = 0; not here!

         asstTotal = numChildren * 1000;

         //return statement here not necessary 

    }


    return asstTotal;


}

这不会编译(请看一下
publicstaticintdeterminateast
),为什么不先编译它呢。也许这样做可以解决你的问题;)请注意,标记不是关键字。在标签列表中填入与问题相同的单词(条件、语句、返回、值),无助于对其进行分类。务必阅读选择标签时出现的说明!