gpt4 book ai didi

java - 尝试将 try 和 catch 添加到代码中,卡住了

转载 作者:行者123 更新时间:2023-12-01 11:30:42 27 4
gpt4 key购买 nike

我需要实现大约 2 个代码块的 try 和 catch。每个人都有自己的需要。我写的代码。我已经为它开设了一个类(class):

public boolean makeOffer(int offer) throws OfferException
{
// reject offer if sale is not open for offers
if (this.acceptingOffers == false)
{
return false;
}

// reject offer if it is not higher than the current highest offer
else if (offer <= this.currentOffer)
{
throw new OfferException("Offer not High enough!");
}

else
{
// new offer is valid so update current highest offer
this.currentOffer = offer;

// check to see if reserve price has been reached or exceeded
if (this.currentOffer >= this.reservePrice)
{
// close the Sale if reserve has been met
this.acceptingOffers = false;
}

return true;
}
}

第二个 block 与第一个 block 非常相似,因为它与第一个 block 位于不同的类中。

public boolean makeOffer(int offer)
{
// reject offer if sale is not open for offers
if (this.acceptingOffers == false)
{
return false;
}

// reject offer if it is not higher than the current highest offer
else if (offer <= this.currentOffer)
{
return false;
}

else
{
// new offer is valid so update current highest offer
this.currentOffer = offer;

// check to see if reserve price has been reached or exceeded
if (this.currentOffer >= this.reservePrice)
{

System.out.println("Name of the Highest Bidder: ");

Scanner s = new Scanner(System.in);
this.highestBidder = s.nextLine();

s.close();
this.acceptingOffers = false;
}
return true;
}

最佳答案

当您使用抛出 Exception 的方法时,您必须使用关键字 throws (除非您抛出 RuntimeException 。这些不必声明为方式)。这样,调用该方法的其他方法就可以处理该异常。

你可以使用这样的东西:

private static void submitOffer() throws OfferException{

// ...
if ( sales[i].getSaleID().equalsIgnoreCase(saleID)){

//try { Remove this try
offerAccepted = sales[i].makeOffer(offerPrice);
if (offerAccepted == true){
System.out.print("Offer was accepted");
if(offerPrice <= sales[i].getReservePrice()){
System.out.print("Reserve Price was met");
}else{
throw new OfferException("Resever not met!");
}
}else{
throw new OfferException("Offer was Not accepted");
}

//....

}

}

当您调用 submitOffer() 方法时,您可以使用:

public void myMethod() throws OfferException{
MyClass.submitOffer();
}

public void myMethod(){
try{
MyClass.submitOffer();
} catch( OfferException oe){
//handle here the exception
}
}

此外,如果您使用自定义Exception,您应该调用 super 构造函数。

public class OfferException extends Exception{

String message;

public OfferException(String message){
super(message); //call the super constructor
this.message = message; //Do you need it ?
}
}

关于java - 尝试将 try 和 catch 添加到代码中,卡住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30422610/

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