【问题标题】:Getting value of variable from method to the main method从方法获取变量的值到主方法
【发布时间】:2021-01-02 09:56:24
【问题描述】:

我在下面有这个程序,我正在调用 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.menu();从上面但 System.out.println("输入来自马耳他的乘客总数:");先从方法,再从菜单。我希望能够在 main 方法的 pm 变量中使用变量 pm from 方法的值。谢谢

【问题讨论】:

  • 我之前已经以不同的形式看到过这个问题(现在很可能已删除)...我记得,我们要求您向我们提供minimal reproducible example 和更多详细信息。问题中提供的代码不完整,无法运行。请编辑您的问题,向我们展示一个最小的示例...

标签: java methods


【解决方案1】:

您无需将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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2020-10-14
    • 2012-11-06
    • 1970-01-01
    • 2011-07-30
    相关资源
    最近更新 更多