gpt4 book ai didi

java - 名称字段在我的 while 循环中第二次没有返回任何内容

转载 作者:行者123 更新时间:2023-12-01 15:47:48 25 4
gpt4 key购买 nike

该程序应该运行两次 while 循环。第一次运行时,会显示姓名、职业、年龄、薪水和带奖金的薪水。然而,当循环第二次运行时,姓名字段为空,带奖金的工资将添加到第一个员工的工资上。谢谢。

import java.util.Scanner;

public class Worker {

public static void main(String[] args) {

String name;
int age;
String occupation;
double salary;
double total = 10000;
int count = 0;

Employee employeeInfo = new Employee();

Scanner keyboard = new Scanner(System.in);

while (count < 2) {

//User Name
System.out.println("Enter your name: ");
name = keyboard.nextLine();
employeeInfo.setEmployeeName(name);

keyboard.nextLine();

//User occupation
System.out.println("Enter your occupation: ");
occupation = keyboard.nextLine();
employeeInfo.setOccupation(occupation);

//User age
System.out.println("Enter your age: ");
age = keyboard.nextInt();
employeeInfo.setAge(age);

//User salary
System.out.println("Enter your salary: ");
salary = keyboard.nextDouble();
employeeInfo.setSalary(salary);
total = total + salary;

//Output information
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Occupation: " + occupation);
System.out.println("Original Salary: " + salary);
System.out.println("Salary with bonus: " + total);

count++;
}

// employeeInfo.greetingMessage("");

}

}





public class Employee {

private String employeeName;// Employee Name
private int age;// Employee Age
private String occupation;// Employee job title
private double salary;// Employee salary

// Setters
public void setEmployeeName(String name) {

employeeName = name;// Initializes employee name

}

public void setAge(int num) {
age = num;// Initializes employee age
}

public void setOccupation(String occu) {

occupation = occu;// Initializes occupation
}

public void setSalary(double num2) {

salary = num2;// Initializes salary
}

// Getters

public String getEmployeeName() {

return employeeName;
}

public int getAge() {

return age;
}

public String getOccupation() {

return occupation;
}

public double getSalary() {

return salary;
}


public void greetingMessage(String greeting){
System.out.println("Greetings " + getEmployeeName());
}
}

最佳答案

扫描仪有问题。您不应该在 nextInt 之后调用 nextLine - 我读到 here 。您需要制作第二个扫描仪并用它来捕获数字,如下所示:

Scanner keyboard = new Scanner(System.in);
Scanner key2 = new Scanner(System.in);

当您想要一个字符串时,请使用第一个,而对于数字,请使用第二个:

name = keyboard.nextLine();
age = key2.nextInt();

此外,请在 while 循环内实例化 Employee 对象,否则每次迭代都会覆盖该对象。

while (count < 2) {
employeeInfo = new Employee();

最后,在获得姓名之后、获得职业之前删除第二个 nextLine

关于java - 名称字段在我的 while 循环中第二次没有返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6784424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com