java 通过调用方法返回Scanner输入,并将其返回到公共类值

lx0bsm1f  于 2023-05-27  发布在  Java
关注(0)|答案(2)|浏览(153)
import java.util.Scanner;

public class UI {
Scanner input = new Scanner(System.in);

    int Store ,Week = play();

    public int play() {

           System.out.print(" Please enter the store #(1-6)");
           Store = input.nextInt();`

           System.out.print("please enter the operation (1-7)");
           Week = input.nextInt();

return Store,Week;
}

}

我怎么可能返回Store和Week值到ui类中。所以我可以用这些值来做进一步的编码。

2nbm6dog

2nbm6dog1#

你不能像在java中那样返回。如果您想调用此方法返回两个值,则应将play的返回类型更改为array。
我的建议是改变play,从构造函数调用它。

import java.util.Scanner;

public class UI {
    Scanner input = new Scanner(System.in);
    int Store, Week;
    
    public UI() {
        play();
    }

    public void play() {
        System.out.print(" Please enter the store #(1-6)");
        Store = input.nextInt();`

        System.out.print("please enter the operation (1-7)");
        Week = input.nextInt();
    }
}
ecbunoof

ecbunoof2#

play方法不需要返回值。
如果值是字段,则可以简单地在方法中对其进行赋值。

public class UI {
    Scanner input = new Scanner(System.in);
    int store, week;

    void play() {
        System.out.print(" Please enter the store #(1-6)");
        store = input.nextInt();
        System.out.print("please enter the operation (1-7)");
        week = input.nextInt();
    }
}

相关问题