【问题标题】:How do I get input from user for two diffrent instances?如何从用户那里获得两个不同实例的输入?
【发布时间】:2020-02-15 14:04:23
【问题描述】:

我正在创建一个显示员工姓名和薪水的程序。名称和薪水由用户输入,我想创建两个员工,即两个实例。如何从用户那里获得两个单独的输入?

import java.util.Scanner;

公共类员工{

String first_name;
String last_name;
double pay = 0;

public Employee(double p, String f, String l) {
    first_name = f;
    last_name = l;
    pay = p;
}

public void name_printer(){
    //To collect Area
   System.out.println("Your name is "+ first_name+" "+last_name+".");   
}

public void pay_printer(){
    //To collect Area
    pay=pay*12;
    System.out.println("Your yearly pay is "+ pay+".");   
}

public void pay_update(){
    //To collect Area
    pay=pay*12;
    pay=pay+(pay*0.1);        
   System.out.println("Your raised yearly pay is "+ pay+".");   
}

public static void main(String[] args) {
    // TODO code application logic here
    Scanner input = new Scanner(System.in);
    System.out.print("Enter first name ");
    String in1_f = input.nextLine();
    System.out.print("Enter last name ");
    String in1_l = input.nextLine();
    System.out.print("Enter your monthly pay ");
    double user1_p = input.nextDouble();
    double in1_p=0;
    if (user1_p>0){
        in1_p=user1_p;
    } 
    Employee employee1 = new Employee(in1_p, in1_f, in1_l);
    employee1.name_printer();
    employee1.pay_printer();
    employee1.pay_update();

}

【问题讨论】:

  • 您的代码正在使用input.nextLine() 从用户那里获取输入。究竟是什么阻止您再使用 3 次来获取下一位员工的信息?...
  • 我以为您想知道如何在设计方面做到正确。在这种情况下,你最好重用代码,我已经发布了一个答案,展示了如何做到这一点

标签: java oop input


【解决方案1】:

为了让您的设计稍微方便一些,您应该遵循程序员的主要习惯之一——重用代码:

// Note that I marked Scanner as final, 
// since it shouldn't be modified inside the method
public Employee createEmployee(final Scanner input) {
    System.out.print("Enter first name ");
    String in1_f = input.nextLine();

    System.out.print("Enter last name ");
    String in1_l = input.nextLine();

    System.out.print("Enter your monthly pay ");
    double user1_p = input.nextDouble();
    double in1_p=0;

    if (user1_p>0){
        in1_p=user1_p;
    } 

    System.out.println("All data is provided, creating instance...");
    return new Employee(in1_p, in1_f, in1_l);
}

然后在主函数中:

Scanner input = new Scanner(System.in);
Employee e1 = createEmployee(input);
Employee e2 = createEmployee(input); // and so on...

要获取有关实例的所有数据,只需覆盖员工类中的 toString() 方法(它比创建自己的打印方法更可取):

@Override
public String toString() {
    StringBuilder s1 = new StringBuilder();
    s1.append("Some information " + someInformation + "\n");
    // construct the string which will represent your object
    return s1.toString();
}

然后:

System.out.println(e1.toString());

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    相关资源
    最近更新 更多