//我编写了具有3种类型的工作者的方法: 经理,所有者和工人
public static int costByType() {
ArrayList<Worker> workers = new ArrayList<>();
String type;
int cost = 0;
System.out.println("Enter type of worker[M/m][W/w][O/o] for finish enter [F/f]:");
type = s.nextLine();
while(!type.equalsIgnoreCase("F")) {
for (Worker w : workers) {
if (type.equalsIgnoreCase("M")) {
cost += ((Manager) w).getSalary() + ((Manager) w).getBonus();
} else if (type.equalsIgnoreCase("W")) {
cost += ((Worker) w).getSalary();
} else if (type.equalsIgnoreCase("O")) {
cost += ((Owner) w).getSalary() + ((Owner) w).getBonus() +Owner.BASE;
}
}
}
return cost;
}
// while循环运行数组列表,找到worker的类型并求和 该代码不返回任何内容。而是一次又一次地循环进行字符扫描**** 谢谢。
答案 0 :(得分:1)
那部分
System.out.println("Enter type of worker[M/m][W/w][O/o] for finish enter [F/f]:");
type = s.nextLine();
需要进入您的循环!
如果您希望用户多次输入值,那么只取一次输入就无济于事!
答案 1 :(得分:0)
这是因为查询了ArrayList“工人”,但从未更新。换句话说,您的ArrayList中不包含任何工作程序。
首先在workers列表中填充worker,将其传递给costByType(workers)之类的函数,而不是在函数内部创建它,然后使用do while循环代替。像这样的东西。
do {
System.out.println("Enter type of worker[M/m][W/w][O/o] for finish enter [F/f]:");
type = src.nextLine();
for (Worker w : workers) {
if (type.equalsIgnoreCase("M")) {
cost += ((Manager) w).getSalary() + ((Manager) w).getBonus();
} else if (type.equalsIgnoreCase("W")) {
cost += ((Worker) w).getSalary();
} else if (type.equalsIgnoreCase("O")) {
cost += ((Owner) w).getSalary() + ((Owner) w).getBonus() +Owner.BASE;
}
}
} while(!type.equalsIgnoreCase("F"));
答案 2 :(得分:0)
**i changed the code:**
public static int costByType(ArrayList<Worker> workers) {
String type;
int cost = 0;
do {
System.out.println("Enter type of worker[M/m][W/w][O/o] for finish enter [F/f]:");
type = s.nextLine();
for (Worker w : workers) {
if (type.equalsIgnoreCase("M") && (w instanceof Manager)) {
cost += ((Manager) w).getSalary() + ((Manager) w).getBonus();
} else if (type.equalsIgnoreCase("W") && (w instanceof Worker)) {
cost += ((Worker) w).getSalary();
} else if (type.equalsIgnoreCase("O") && (w instanceof Owner)) {
cost += ((Owner) w).getSalary() + ((Owner) w).getBonus() + Owner.BASE;
}
}
return cost;
} while (!type.equalsIgnoreCase("F"));
}
//现在显示成本后,它不会循环。它应该再次运行并显示成本,直到String为f