gpt4 book ai didi

java - 奇怪的程序行为

转载 作者:行者123 更新时间:2023-12-01 23:27:08 26 4
gpt4 key购买 nike

这个基本程序让我抓狂。一定有一些非常简单的东西我在这里看不到。为什么会触发异常?

有 2 类:1)

public class Person
{
private String name;
private int age;
private static int numberOfPeople = 0;

public Person()
{
this("John Doe", 0);
numberOfPeople++;
}
public Person(String name, int age)
{
this.setAge(age);
this.setName(name);
numberOfPeople++;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public int getNumberOfPersons()
{
return numberOfPeople;
}
public String toString()
{
return this.name + " " + this.age;
}

}

2)

import java.util.Random;

public class Adult extends Person
{
private String number;
public static final int MIN_AGE = 18;

public Adult(String name, int age, String number)
{
super(name, 0);
this.setAge(age);
this.number = number;
}
public Adult(Adult adult)
{
this(adult.getName(), adult.getAge(), adult.getNumber());
}
public Adult()
{
this.number = "";
this.setAge(MIN_AGE);
Random rand = new Random();
int result = rand.nextInt(2);
if (result == 0)
{
this.setName("John Doe");
}
else
{
this.setName("Jane Doe");
}
}
public void setAge(int age)
{
if (age < MIN_AGE)
{
throw new IllegalArgumentException("The person must be 18 or older!");
}
else
{
super.setAge(MIN_AGE);
}
}
public String getNumber()
{
return this.number;
}
private void setNumber(String number)
{
this.number = number;
}
public String toString()
{
return this.getName() + " " + this.getNumber() + " " + this.getAge();
}
public boolean equals(Object obj)
{
boolean result = false;
if (obj != null && this.getClass() == obj.getClass())
{
Adult other = (Adult) obj;
if (this.getName().equals(other.getName()) &&
this.getNumber().equals(other.getNumber()) &&
this.getAge() == other.getAge())
{
result = true;
}
}
return result;
}
public static void main(String[] args)
{
Adult ad = new Adult();
System.out.println(ad);
}
}

这给了我以下错误:

Exception in thread "main" java.lang.IllegalArgumentException: The person must be 18 or older!
at people.Adult.setAge(Adult.java:39)
at people.Person.<init>(Person.java:16)
at people.Adult.<init>(Adult.java:12)
at people.Adult.main(Adult.java:75)

最佳答案

你的Person()构造函数创建了另一个人。由于 Adult 扩展了 Person,因此存在隐式 super() 调用,这可能是导致错误的原因。

关于java - 奇怪的程序行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19827000/

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