gpt4 book ai didi

java - 为什么java程序可以编译但不能运行?

转载 作者:行者123 更新时间:2023-12-02 10:50:29 25 4
gpt4 key购买 nike

我有一个名为 Employee 的类,它有 2 个 private 变量,并且还包含其所需的构造函数和其他必要的方法:

public class Employee {

private String name;
private int id;

public Employee() {
name = " No Name!";
id = 00100;
}

public Employee(String n, int i) {
name = n;
id = i;
}

public Employee(Employee originalObject) {
name = originalObject.name;
id = originalObject.id;
}

public String getName() {
return name;
}

public int getID() {
return id;
}

public void setName(String newName) {
if (newName == null) {
System.out.println("Fatal Error setting employee name!");
System.exit(0);
} else {
name = newName;
}
}

public void setID(int newID) {
id = newID;
}

public String toString() {
return (name + " " + id);
}

public boolean equals(Employee otherEmployee) {
return (name.equals(otherEmployee.name)
&& id == otherEmployee.id);
}
}

这个Employee类扩展了另一个名为HourlyEmployee的类。扩展类如下:

public class HourlyEmployee extends Employee {

private double wageRate;
private double hours;

public HourlyEmployee() {
super();
wageRate = 0;
hours = 0;
}

public HourlyEmployee(String na, int di, double wR, double h) {
super(na, di);
if (wR >= 0 || h >= 0) {
wageRate = wR;
hours = h;
} else {
System.out.println("Fatal Error!: creating illegal hourly employee");
}
System.exit(0);
}

public HourlyEmployee(HourlyEmployee originalObject) {
super(originalObject);
wageRate = originalObject.wageRate;
hours = originalObject.hours;
}

public double getRate() {
return wageRate;
}

public double getHours() {
return hours;
}

public double getPay() {
return wageRate * hours;
}

public void setRate(double newWR) {
if (newWR >= 0) {
wageRate = newWR;
} else {
System.out.println("Fatal Error: negative hours worked!");
System.exit(0);
}
}

public String toString() {
return (getName() + " " + getID() + "\n$" + wageRate + " per hour for " + hours + "hours");
}
}

完成此类的编码后,我编写了演示类来测试这些类及其工作原理。

public class InheritanceDemo {

public static void main(String[] args) {
HourlyEmployee joe = new HourlyEmployee("Joe Worker", 281952, 50.50, 160);
System.out.println("joe's longer name is " + joe.getName());
System.out.println("Changing joe's name to joseph.");
joe.setName("Joseph");
System.out.println("joe's record is as follows: ");
System.out.println(joe);
}
}

最后,我尝试编译代码,效果很好,但不幸的是,演示类没有运行,尽管它在屏幕上显示“进程已完成”!您认为这个程序有什么问题?

最佳答案

问题出在 HourlyEmployee 中的第一个 System.exit(0)。由于 else 之后没有 {},因此无条件执行退出。

关于java - 为什么java程序可以编译但不能运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9252347/

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