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

问题描述 投票:0回答:1

我正在尝试采用构造函数(字符串、字符串、双精度)并使用扫描仪输入设置其中的值。

我的程序可以分配我输入的值,但我希望能够从键盘分配它们。我只想使用一种构造函数方法来完成此任务。

我把它分成两类:

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 employee 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.printf("Employee %s %s makes $%f this month and with a 10% raise, their new pay is $%f%n", fname, lname, pay, (pay * 0.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;
    }
    
}
input java.util.scanner
1个回答
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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.