inputjava.util.scanner

How do you input data into a constructor from scanner?


I am trying to take a constructor (string, string, double) and set the value in it with a scanner input.

My program can assign the values that I put in, but I want to be able to assign them from the keyboard. I would like to use only one constructor method to accomplish this.

I have it broken up into two classes:

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;
    }
    
}

Solution

  • You can modify you EmployeeTest class something like

    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();
        }
    }