[英]How to take user input from main method to another class and method?
我想我的标题不是很清楚,需要一个代码示例,所以在这里你去:
public class ATM {
public static void main(String[] args) {
Keypad K=new Keypad();
K.mypin(pin);
}
}
这是主要方法,现在这是另一个类中的方法:
public class Keypad{
public void mypin(int pin) {
System.out.print("Please enter your pin");
pin=scan.nextInt();
System.out.print(pin);
}
}
如何包含pin=scan.nextInt();
在我的主要方法中,使这项工作正常吗? 你可能会问我为什么这么想,这只是因为我被要求做的事情。
如果我理解正确,你需要这样的东西:
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);
}
}
您可以将Scanner类与输入流System.in一起使用 。
它是ATM类:
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();
}
}
}
它是键盘类:
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();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.