Reputation: 29
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.
Upvotes: 1
Views: 2436
Reputation: 1
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();
}
}
}
}
Upvotes: 0
Reputation: 24812
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);
}
}
Upvotes: 4