我有一个程序,它声明了一个Apartment对象数组。每个公寓都有一个地址,一个数字,一个卧室数和一个租金价格。初始化数组时,将为每个单元提供一个字符串,并且Apartment类的构造函数将该字符串转换为值。该程序是使用多个类进行异常引发和捕获的测试研究。
当前一切正常,创建了Apartments,将字符串正确转换为对象参数,并正确引发并捕获了异常,但是,当前,当捕获异常时,程序结束。我不确定该怎么办。我相信我可以重组程序,以便将异常捕获在Apartment构造函数本身中,但是如果这样做不起作用,那将是浪费大量时间,因此我决定在此处搜索然后提出问题。第一。
这是程序中“主”类的代码,其下面是当前输出:
public class ThrowApartmentException
{
public static void main(String[] args)
{
// this program uses three classes, the ThrowApartmentException class is the "main" class, it's what you run to use the program. The Apartment class is used to create
// apartment objects, and it converts apartment Strings into values, checks those values for validity, and throws an exception if those values are wrong. This exception
// is an ApartmentException, which is the third class. It takes the apartment string as an argument and simply prints a message stating that the apartment failed to be
// instantiated.
// this class creates an array of 6 apartment objects, with both valid and invalid values, and an appropriate message is displayed when one is instantiated successfully
// and one is not.
Apartment[] apartments = new Apartment[6];
// apartment string parameter is formatted "address, number, rooms, rent".
try {
apartments[0] = new Apartment("123 Fake Street, 456, 3, 1500"); // valid.
apartments[1] = new Apartment("21 Blizzard Avenue, 333, 2, 2600"); // invalid rent.
apartments[2] = new Apartment("6 Brr Street, 23, 1, 1000"); // invalid number.
apartments[3] = new Apartment("25 Boat Lane, 324, 5, 1200"); // invalid rooms.
apartments[4] = new Apartment("47 Kenneth Street, 550, 1, 1000"); // valid.
apartments[5] = new Apartment("36 Sanders Drive, 230, 1, 1300"); // valid.
}
catch(ApartmentException mistake) {
}
}
}
-----------------------------------------
Output:
Apartment 123 Fake Street, 456, 3, 1500 was successfully initialised.
Apartment 21 Blizzard Avenue, 333, 2, 2600 failed to be instantiated, one or more of the values was outside of valid range.
我认为可以解决该问题的当前可用选项包括:
1:将每个对象实例化放在其自己的try / catch块中。
2:重组程序,以便在Apartment构造函数内部执行try / catch块。
3:被告知某种格式化循环的方式,该循环允许像这样的独特对象实例化,我可能可以使用String数组,但这似乎是一个难以置信的笨拙的胶带解决方案,而不是实际的解决方案。
最佳答案
这就是我要做的:
1-如果将无效的输入传递给Apartment Class
,则将其抛出异常(在您的情况下为ApartmentException
)
2-使用列表代替数组,如下所示:
List<Apartment> myList = new ArrayList<Apartment>();
String[] desc = new String {"123 Fake Street, 456, 3, 1500", ... }
for(int i=0; i<desc.length; i++)
{
try
{
myList.add(new Apartment(desc[i]));
}
catch(ApartmentException mistake)
{
//do something
}
}
//at this point myList contains only valid listings