java - 从方法获取变量的值到主方法
问题描述
我在下面有这个程序,我正在调用 getTotalPassenger(pm) 方法,但在获取用户输入的值时遇到问题。
do {
/*Menu being called from method and gives 6 options to the user.
Chosen option will be stored in "choice" variable.*/
printmenu.menu();
choice = sc.nextInt();
//Creating a switch statement for the 6 menu options.
switch (choice) {
case 1 : /* Asks user to input total number of passengers
and a while loop to check if a positive number input is entered.
If a negative input is entered the user is asked again to enter a positive entry.
All inputs are stored in a variable.
After a positive entry program continues to next question. */
getTotalPassengers(pm);
方法代码是:
public static int getTotolPassengers(int pm) {
while (pm <= 0) {
System.out.println("Enter total number of passengers from Malta :");
pm = sc.nextInt();
if (pm <= 0) {
printpositive.positive ();
continue;
}
}
return pm;
}
我尝试了不同的方法,例如将其初始化为 int choice = 0,
pm = 0,cm = 0,pi = 0,ci = 0,ps = 0,cs = 0,或者当我尝试这样做时 pm= getTotalPassengers(pm = 0) 它可以工作,但不会向用户显示主菜单 printmenu 。菜单(); 从上面但 System.out.println("输入来自马耳他的乘客总数:"); 先从方法,再从菜单。我希望能够在 main 方法的 pm 变量中使用变量 pm from 方法的值。谢谢
解决方案
你不需要pm
传入getTotalPassengers()
. 定义pm
为局部整数变量并初始化为 0。pm
一旦用户输入了有效值,就从函数返回。
public static int getTotalPassengers() {
int pm = 0;
while (pm <= 0) {
System.out.println("Enter total number of passengers from Malta :");
pm = sc.nextInt();
if (pm <= 0)
printpositive.positive(); // let user know they've entered a bad value
}
return pm;
}
然后在case
语句中使用getTotalPassengers()
.
推荐阅读
- spring-boot - 使用 Swagger 3 和 Springboot 启用 JWT 授权
- azure - Azure 门户 - 迁移到 ARM - 在准备步骤中失败
- amazon-web-services - Amazon MQ 是否在集群部署模式下部署网络负载均衡器?
- java - SwipeRefershLayout 在 Android 中不起作用
- power-automate - 在 Power-Automate 中创建新 Dataverse 记录时出现问题
- python - 从 Firebase 查询时遇到问题
- vue.js - Vuetify 字体在生产和开发中是不同的
- php - 无论如何在laravel视图中使用JSON数据实现过滤?
- java - 是否可以使用 Realm 公开光标?
- python - 在 Python 中选择 MySQL 数据库