可能是这样的:
如果您想使用您在 ActionClass 类的示例 main() 方法中指出的 Scanner 对象,那么您需要在接受 Scanner 对象的方法类:
package whateverpackage;
import java.util.Scanner;
public class Method {
// Declare a Scanner Object field.
// This will make the Object global
// to the entire Class.
private Scanner scannerInput;
// Class Constructor
public Method (Scanner input) {
this.scannerInput = input;
}
public void passingParameters(){
System.out.println("Enter a integer value for Parameter: ");
int numInput = scannerInput.nextInt();
input.nextLine(); // Empty scanner buffer
System.out.println("Supplied value was: " + numInput);
}
}
然后是你的 ActionClass:
package whateverpackage;
import java.util.Scanner;
public class ActionClass {
public static void main(String[] args) {
Method newObject = new Method(new Scanner(System.in));
newObject.passingParameters();
}
}
如果您打算将 Method 类中的 Scanner 对象广泛用于各种方法,这将特别方便。但是,如果您只打算在 Method 类中偶尔使用 Scanner 对象,那么我认为 @user7 在评论中描述的方式可能是进入的方式在这种情况下不需要构造函数来执行任务:
package whateverpackage;
import java.util.Scanner;
public class Method {
// Method accepts a Scanner Object as an argument.
public void passingParameters(Scanner input){
System.out.println("Enter a integer value for Parameter: ");
int numInput = input.nextInt();
input.nextLine(); // Empty scanner buffer
System.out.println("Supplied value was: " + numInput);
}
}
然后是你的 ActionClass:
package whateverpackage;
import java.util.Scanner;
public class ActionClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Method newObject = new Method();
newObject.passingParameters(scanner);
}
}
Scanner 对象也可以声明为 Class 字段,并且在 ActionClass 类中是全局的,然后可以从该类中的任何方法中使用,而无需总是声明 Scanner 的新实例。然而,由于 main() 方法是静态方法,因此需要将 Object 声明为 static。 ActionClass 类中使用此 Scanner 对象的任何方法也需要声明为静态。在这种情况下没什么大不了的,但总会有一段时间(here's some interesting reading about static)。为了解决这个问题,不要在 main() 方法中使用对象,完全使用不同的方法:
package whateverpackage;
import java.util.Scanner;
public class ActionClass {
private Scanner scanner = new Scanner(System.in);
// *****************************************
public static void main(String[] args) {
new ActionClass().startApp(args);
}
// *****************************************
private void startApp(String[] args) {
Method newObject = new Method();
newObject.passingParameters(scanner);
justAnotherMethod();
}
private void justAnotherMethod () {
System.out.println("What's your name: ");
String name = scanner.nextLine();
System.out.println("Your Name is: " + name);
}
}