如何从扫描仪将数据输入构造函数?

时间:2014-09-23 18:26:43

标签: input java.util.scanner

我正在尝试使用构造函数(string,string,double)并使用扫描仪输入设置其中的值。任何帮助表示赞赏。代码列在下面。

我的程序可以分配我输入的值,但我希望能够从键盘分配它们,我想只使用一个构造函数方法来实现这一点。感谢

我将它分为两​​类:

import java.util.Scanner;

public class EmployeeTest 
{
    public static void main(String [] args)
    {
        Scanner input = new Scanner(System.in);

        Employee employee1 = new Employee("james", "ry", 3200);
        Employee employee2 = new Employee("jim" , "bob" , 2500.56 );

        System.out.println("What is employyee 1's first name? ");
        employee1.setFname(input.nextLine());



    }
}

class Employee 
{
    private String fname;
    private String lname;
    private double pay;

    public Employee(String fname, String lname, double pay)
    {
        this.setFname(fname);
        this.lname = lname;
        this.pay = pay;

        System.out.println("Employee " + fname +" "+ lname + " makes $" +
                + pay + " this month and with a 10% raise, their new pay is $" + (pay * .10 +     pay));

    }   
     void setfname(String fn)
   {
    setFname(fn);
    }
    void setlname(String ln)
    {
        lname = ln;
    }
    void setpay (double sal)
    {
        pay = sal;
    }

    String getfname()
    {
        return getFname();
    }
    String getlname()
    {
        return lname;
    }
    double getpay()
    {
        if (pay < 0.00)
        {
            return pay = 0.0;
        }

        return pay;
    }
    public String getFname() {
    return fname;
    }
    public void setFname(String fname) 
    {
        this.fname = fname;
    }

}

1 个答案:

答案 0 :(得分:0)

您可以修改EmployeeTest

class EmployeeTest {

    public static void main (String...arg) {
        Scanner s = new Scanner(System.in);

        String[] elements = null;
        while (s.hasNextLine()) {
            elements = s.nextLine().split("\\s+");
            //To make sure that we have all the three values
            //using which we want to construct the object
            if (elements.length == 3) {
                //call to the method which creates the object needed
                //createObject(elements[0], elements[1], Double.parseDouble(elements[2]))
                //or, directly use these values to instantiate Employee object
            } else {
                System.out.println("Wrong values passed");
                break;
            }
        }
        s.close();
    }
}