java—获取从方法到主方法的变量值

uttx8gqw  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(562)

下面有一个程序,我正在调用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变量中使用变量pmfrom方法的值。谢谢

3mpgtkmj

3mpgtkmj1#

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

相关问题