如何 return 一个方法中的数组并在 Java 中的另一个方法中使用它

How to return an array from a method and use it in another method in Java

我创建了一个包含三个整数的数组,要求用户输入,然后我 return 该数组并实例化了 class,但我无权访问数组项:

import java.util.Scanner;

public class Input {
    public static int[] getInput() {
        Scanner sc = new Scanner (System.in);
        int choice[] = new int[3];
        System.out.println("Type the options: ");
        System.out.println("Plate: ");
        choice[0] = sc.nextInt();
        System.out.println("Dessert: ");
        choice[1] = sc.nextInt();
        System.out.println("Drink: ");
        choice[2] = sc.nextInt();
        return choice;
      }
}

主要class:

public class Main
{
    public static void main (String [] args) {

        Menu menu = new Menu();
        Input input = new Input();

        menu.ShowMenu();
        Input.getInput();


        //I want to compare choice[0] here
       if (input.getInput() == 1) {
            //code block
           }

这三个选择需要写方法吗?我只想传递三个用户输入以在 Main class if 和 else 中使用。

将 return 值保存在变量中。

int[] choices = Input.getInput();

if (choices[0] == 1) {
    ...
}

而不是 Input.getInput(),写入 int[] arr=Input.getInput()。您必须将方法的结果存储在变量中。

您可以使用 arr[index] 访问元素,索引从 0 开始,例如 a[0]

int[] inputs = Input.getInput();

if (inputs[0] == 1) { ... }

那是一个数组并且是静态的...因此您可以保存此声明:

 Input input = new Input();

而且你只能做:

if (Input.getInput()[0] == 1) {
       //code block
}