How take user input in one method and use it in another

11,755

Solution 1

Make a method which return a number and call it from another method.

public static int first()
{
    System.out.print("Enter number: ")
    Scanner scan = new Scanner(System.in);
    int number = scan.nextInt();
    return number;
}

public static void getNumber(String name, int move)
{
    int number = first();   //Call method here.
    if (number == 1)
    {
        System.out.println("Player shows one" );
    }
}

Solution 2

Define number as a class attribute.
Something like (its not final/working code)

class myClass{
  int number = 3;  // Or any other default value   

  public static void first()
  {
    //....
    obj.number = scan.nextInt();
    //...
  }  

 public static void getNumber(String name, int move)
 {
    if (obj.number == 1)
    {
       //...... 
    } 
 }

}
Share:
11,755
user2181402
Author by

user2181402

Updated on June 04, 2022

Comments

  • user2181402
    user2181402 almost 2 years

    I am very new to java and have searched around and can't seem to find what to do. I need to take int number and be able to use it in another method. I have to use two methods to do this. I am unsure how to call upon it.


    public static void first()
    {
        System.out.print("Enter number: ")
        Scanner scan = new Scanner(System.in);
        int number = scan.nextInt();    
    }
    
    public static void getNumber(String name, int move)
    {
    
        if (number == 1)
        {
            System.out.println("Player shows one" );
        }