Rafa_Asp1
Rafa_Asp1

Reputation: 89

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

I created an array of three integers that I ask input to the user, then I return that array and instantiated the class, but I don't have access to the array items:

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;
      }
}

Main 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
           }

Do I need to write a method to the three choices? I just want to pass the three user inputs to use in the Main class if's and else's.

Upvotes: 0

Views: 75

Answers (4)

That is an array and is static... so you can save this declaration:

 Input input = new Input();

and you must only do:

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

Upvotes: 1

Jason Qiao Meng
Jason Qiao Meng

Reputation: 37

int[] inputs = Input.getInput();

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

Upvotes: 1

Thomas Böhm
Thomas Böhm

Reputation: 1486

Instead of Input.getInput(), write int[] arr=Input.getInput(). You have to store the result of the Method in a variable.

You can than access the Elements with arr[index], index starting with 0, for example a[0]

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361625

Save the return value in a variable.

int[] choices = Input.getInput();

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

Upvotes: 1

Related Questions