Java方法调用问题求助:checkEntry方法返回值始终为0
Java方法返回值始终为0的问题解决
问题描述
因大学课程要求5周速成Java,时间紧张,完成ZyBooks的Java实验时遇到问题:调用checkEntry方法后返回值始终为0。
实验要求
- 按提示
"Please enter a number between 15 and 45. Enter 1 to exit."获取用户输入,用while循环实现程序,输入1则退出; - 循环内依次执行:输出提示、获取整数输入、打印
"Output: "并调用checkEntry方法传入输入值; checkEntry方法逻辑:若输入值≥35则加10返回,若小于35则乘5返回。
原代码
import java.util.Scanner; public class LabProgram { public static void main(String[] args) { /* Type your code below this line. Create additional lines as needed. */ Scanner scnr = new Scanner(System.in); int userNum; userNum = 0; while (userNum != 1) { System.out.println("Please enter a number between 15 and 45. Enter 1 to exit."); userNum = scnr.nextInt(); System.out.println("Output: " + checkEntry(userNum)); } } // do not delete this line public static int checkEntry(int incoming) { /* Type your code for the checkEntry method below this line. Create additional lines as needed. */ int userNum; userNum = 0; if (userNum >= 35) { userNum = userNum + 10; } else { userNum = userNum * 5; } return userNum; } // do not delete this line } // do not delete this line
问题原因
checkEntry方法逻辑错误:方法内部新建了初始值为0的userNum变量,所有判断和计算都基于这个固定的0,完全没有使用传入的参数incoming。0不满足≥35的条件,执行0*5结果还是0,因此无论传入什么值,返回结果始终是0。
修正后的代码
import java.util.Scanner; public class LabProgram { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int userNum = 0; while (userNum != 1) { System.out.println("Please enter a number between 15 and 45. Enter 1 to exit."); userNum = scnr.nextInt(); System.out.println("Output: " + checkEntry(userNum)); } } public static int checkEntry(int incoming) { // 直接使用传入的参数进行判断和计算 if (incoming >= 35) { return incoming + 10; } else { return incoming * 5; } } }
修正说明
- 删除
checkEntry方法内多余的userNum变量,直接使用方法参数incoming执行逻辑判断; - 简化返回逻辑,满足条件时直接返回计算结果,无需额外变量存储;
- 主方法内的变量初始化可简化为
int userNum = 0;,不影响原有功能。
内容的提问来源于stack exchange,提问作者Nikita Childers
相关产品推荐
相关产品推荐

