首页 > 解决方案 > 从方法获取变量的值到主方法

问题描述

我在下面有这个程序,我正在调用 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 方法的值。谢谢

标签: javamethods

解决方案


你不需要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().


推荐阅读