简体   繁体   中英

How to take user input from main method to another class and method?

I guess my title isn't very clear and needs a code example so here you go:

public class ATM {


public static void main(String[] args) {

     Keypad K=new Keypad();
     K.mypin(pin);
}
}

That is the main method, now here is a method in another class:

public class Keypad{
    public void mypin(int pin) {
        System.out.print("Please enter your pin");
        pin=scan.nextInt(); 
        System.out.print(pin);  
    }
}

How to include pin=scan.nextInt(); in my main method and make this work normally? You might ask me why I want it this way and it is just because that is what I was asked to do.

If I understood you correctly, you want something along those lines :

public class ATM {
    public static void main(String[] args) {
        System.out.print("Please enter your pin");
        Scanner sc = new Scanner(System.in);
        Keypad K=new Keypad();
        K.mypin(sc.nextInt());
    }
}

public class Keypad{
    public void mypin(int pin) {
        System.out.print(pin);  
    }
}

You can use Scanner class with input stream System.in .

It is ATM class:

package user.input;

public class ATM {

  public static void main(String[] args) {
    Keypad keypad = new Keypad();

    try {
      int userPin = keypad.enterPin();
      System.out.printf("User Pin: %s", userPin);
    } catch (Exception e) {
      System.err.println("Occured error while entering user's PIN.");
      e.printStackTrace();
    }

  }
}

It is Keypad class:

package user.input;

import java.util.Scanner;

    public class Keypad {

      public int enterPin() throws Exception {
        Scanner scanner = null;
        try {
          scanner = new Scanner(System.in);
          System.out.print("Please enter your pin: ");
          int inputNum = scanner.nextInt(); // Read user input
          return inputNum;
        } catch (Exception e) {
          throw e;
        } finally {
          if (scanner != null) {
            scanner.close();
          }
        }
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM