如何将用户输入变量传递给构造函数?

时间:2009-12-02 01:45:42

标签: java constructor

我只需要一些帮助。 用户必须输入id,密码,最大尝试次数和数量。最大使用次数。 他们必须进入构造函数...... 有人可以帮助我将它们传递给构造函数吗? 我正在使用java。 谢谢!

import java.util.Scanner;
public class LoginPw{


 public static void main(String[] args){
  // TODO Auto-generated method stub
  Scanner reader = new Scanner(System.in);
  System.out.println("Enter in your id and password");
  int idnum = reader.nextInt();
  int password = reader.nextInt();
  System.out.println("Enter in the max number of tries");
  int maxtries = reader.nextInt();
  System.out.println("Enter in the number of max uses");
  int maxuses = reader.nextInt();
  PwLogin pwl = new PwLogin(idnum,password,maxtries,maxuses); 

 }}
class PwLogin{

  public PwLogin(int id, int pw){
   //assumes max num of tries is infinite. denote by value of 0.
   this(id,pw,0,0); //call the 4-argument constructor w/ maxTries & maxUses defaulted as zero(infinite)
  }
  public PwLogin(int id, int pw, int tries){
   //assumes max number of uses is infinite. denote by value of 0.
   this(id, pw, tries,0); //Call the 4-argument constructor with maxUses defaulted as zero (infinite)
  }
  public PwLogin(int id, int pw, int tries, int uses){
   // Now set the 4 class variables from the passed-in arguments
   this.idnum =id; 
   this.password = pw;
   this.maxtries=tries;
   this.maxuses=uses;

  }  

 }

1 个答案:

答案 0 :(得分:2)

您需要在Java中声明成员变量:

class PwLogin{

    private int idnum; 
    private int password; 
    private int maxtries; 
    private int maxuses; 

    public PwLogin(int id, int pw){
        etc...