我正在尝试使此代码正常工作,而我的问题在于使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;
}


在原始代码中,直到在if块中才声明asstTotal变量。这意味着一旦if块退出,该变量将不再存在。它在错误的scope中,因此return语句将无法编译。

另外,如@donfuxx所述,if块内的return语句也是不必要的。它可以工作,但是很多余。

这样可以解决您的问题吗?

09-27 18:31